微信小程序结合vant weapp ui实现多图上传组件

微信小程序多图上传

最近在写小程序的商品上传,为方便需要使用多张图片的上传的功能。因为小程序不支持数组的多张图片同时上传,然后根据自己的需求创建了一个组件希望能够帮到大家

效果图

在这里插入图片描述

  1. 创建一个图片上传的promise
	uploadFilePromise(filePath, Authorization) {
            return new Promise(function(resolve, reject) {
                wx.uploadFile({
                    url: `${DOMAIN}File/Image/upload`,
                    filePath,
                    name: 'file',
                    header: {
                        Authorization,
                    },
                    success: res => {
                        // 触发图片上传事件
                        let data = JSON.parse(res.data);
                        if (data.code != SUCCESS_CODE) {   //SUCCESS_CODE为本项目请求成功的判断无需在意
                            wx.showToast({
                                title: data.message || '上传失败',
                                icon: 'none'
                            })
                        } else {
                            resolve(res)
                        }
                    },
                    fail: res => {
                        reject(res)
                    }
                });
            })
        },
  1. 创建一个promise.all (多个图片上传成功后再改变dom)
	chooseImage(){
			wx.chooseImage({
                count,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success(res) {
                    const tempFilePaths = res.tempFilePaths;  //拿到选择的图片地址
                    that.triggerEvent('disableBtn', {}, {});  //上传过程中禁用父组件中的保存按钮,防止图片未上传成功
                    let promiseList = tempFilePaths.map(temp => that.uploadFilePromise(temp, Authorization));  //获取promise 队列数组
                    Promise.all(promiseList).then((result) => {
                        let uploadImgList = result.map(item => ({ file_key: JSON.parse(item.data).data.key, url: JSON.parse(item.data).data.url })).reverse();
                        imgList.unshift(...uploadImgList);  //将新上传的图片从头部插入原图片数组中
                        that.triggerEvent('Upload', { imgList, key })  //上传成功将新的图片数组给到组件
                    })
                }
            })
 	}
  1. 完整js 文件
 	import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import {
    DOMAIN,
    TOKEN_KEY,
    SUCCESS_CODE
} from "../../../../configs";
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        imgList: {  //图片列表
            type: [Array],
            value: [],
        },
        max: {  //最大可以上传数
            type: [Number],
            value: 10
        },
        key: { //图片列表key
            type: [String],
            value: ''
        }
    },

    /**
     * 组件的初始数据
     */
    data: {

    },
    
    methods: {
        upload(e) {
            const {key,max} = e.target.dataset;
            let imgList = this.data.imgList,
                listLen=imgList.length,
                count = parseInt(max - listLen) > 9 ? 9 : parseInt(max - listLen),
                that = this;
            var Authorization = wx.getStorageSync(TOKEN_KEY);
            if (listLen >= max) {
                wx.showToast({
                    title: `最多上传${max}张图片`,
                    icon: 'none',
                    duration: 2000
                });
                return false;
            }
            wx.chooseImage({
                count,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success(res) {
                    const tempFilePaths = res.tempFilePaths;
                    that.triggerEvent('disableBtn', {}, {});
                    let promiseList = tempFilePaths.map(temp => that.uploadFilePromise(temp, Authorization));
                    Promise.all(promiseList).then((result) => {
                        let uploadImgList = result.map(item => ({ file_key: JSON.parse(item.data).data.key, url: JSON.parse(item.data).data.url })).reverse();
                        imgList.unshift(...uploadImgList);
                        that.triggerEvent('Upload', { imgList, key })
                    })
                }
            })
        },
        uploadFilePromise(filePath, Authorization) {
            return new Promise(function(resolve, reject) {
                wx.uploadFile({
                    url: `${DOMAIN}File/Image/upload`,
                    filePath,
                    name: 'file',
                    header: {
                        Authorization,
                    },
                    success: res => {
                        // 触发图片上传事件
                        let data = JSON.parse(res.data);
                        if (data.code != SUCCESS_CODE) {
                            wx.showToast({
                                title: data.message || '上传失败',
                                icon: 'none'
                            })
                        } else {
                            resolve(res)
                        }
                    },
                    fail: res => {
                        reject(res)
                    }
                });
            })
        },
        delete(e) {
            const { key, index } = e.target.dataset;
            Dialog.confirm({
                selector: '#create-dialog',
                title: '提示',
                message: '确认删除该图吗?'
            }).then(() => {
                this.triggerEvent('Delete', {key,index})
            }).catch(() => {
                // on cancel
            })
        },
    }
})
  1. 创建一个wxml
<view class="product-img-list">
	<view class="img-box" wx:for="{
   
   {imgList}}" wx:key="index">
		<van-image src="{
   
   {item.url}}" mode="widthFix"   lazy-load custom-class="product-img"></van-image>
		<view bindtap="delete" data-index="{
   
   {index}}" data-key="{
   
   {key}}">删除</view>
	</view>
	<image src="http://image.end.wiki/[email protected]?imageslim" data-key="{
   
   {key}}" data-max="{
   
   {max}}" class="add-image-icon" bindtap="upload" mode="aspectFit|aspectFill|widthFix" lazy-load="false" binderror="" bindload=""></image>
</view>
  1. 写上样式wxss
.product-img-list {
    display: flex;
    flex-wrap: wrap;
}

.product-img-list .img-box {
    width: 100rpx;
    margin-right: 24rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #909090;
    font-size: 28rpx;
    margin-top: 32rpx;
}

.img-box .product-img{
    width: 100rpx;
    height: 100rpx;
    margin-bottom: 24rpx;
}

.add-image-icon {
    width: 100rpx;
    height: 100rpx;
    margin-top: 32rpx;
}
  1. 父组件的调用–wxml
<banner-uploader max="10" imgList="{
   
   {form.bannerList}}" key="bannerList" bindUpload="uploadProImg" bindDelete="deleteProImg" binddisableBtn="disableBtn"></banner-uploader>

7.父组件的调用 --js

 //上传图片
    uploadProImg(e) {
        let form = this.data.form,
            key = e.detail.key,
            imgList = e.detail.imgList;
        form[key] = imgList;
        this.setData({ form, btnDisabled: false })
    },
    //上传按钮禁用
    disableBtn(e) {
        this.setData({ btnDisabled: true })
    },
    //删除图片
    deleteProImg(e) {
        let form = this.data.form,
            key = e.detail.key,
            index = e.detail.index,
            keyList = form[key];
        keyList.splice(index, 1);
        form[key] = keyList;
        this.setData({ form })
    },

猜你喜欢

转载自blog.csdn.net/qq_41194534/article/details/105791299