uniapp 运用Promise实现多图片上传

使用业务场景,循环多个图片上传控件,每一个上传到指定字段;

dom结构如下:

<u-form :model="userForm" :rules="rules" ref="uForm" labelWidth="160">			
			<u-form-item v-for="(item,index) in userForm.constructProcessList" :key="index" labelWidth="70" borderBottom>
				<block slot="label" v-if="index<=5">{{ item.key }}:</block> 
				<block slot="label" v-else>    
				  <u-input v-model.trim="item.key" :placeholder="`请输入${item.key}`"></u-input>
				</block>  
				<view style="display: flex; flex-wrap: wrap;">
				<view class="uni-uploader__input-box">
					<view class="uni-uploader__input" @tap="chooseImage(index)"></view>
				</view>
				<view class="uni-uploader__files" v-if="item.value!=null">
					<block v-for="(src,i) in item.value" :key="i">
						<view class="uni-uploader__file wrapAll">
							<uni-icons type="close" size="19" color="#b6b6b6" class="imgwrap"
								@click="deletePic(index,i)"></uni-icons>
							<image class="uni-uploader__img" mode="aspectFill" :src="src" :data-src="src" @tap="previewImage($event,i)"></image>
						</view>						
					</block>
				</view>	
				</view>
				
				<view style="font-size: 12px; color: #666;">仅支持.jpg, .jpeg, .png文件,最多能上传9个,且单个文件不超过20M</view>
				<view style="width: 50px; margin: 0 auto;">
					<u-button type="error" shape="circle" icon="minus" @click="deleteItem(item, index)" v-if="index>5"></u-button>
				</view>					
			</u-form-item>
			<u-form-item labelWidth="70">
				<view style="width: 50px; margin: 0 auto;">
					<u-button type="primary" shape="circle" icon="plus" @click="addItem"></u-button>
				</view>				
			</u-form-item>			
		</u-form>

js部分:

var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	]

data() {
			return {				
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9],		
				userForm: {					
					wellId: null,	
					constructProcessList:[
						{key:'字段1',value:[]},
						{key:'字段2',value:[]},
						{key:'字段3',value:[]},
						{key:'字段4',value:[]},
						{key:'字段5',value:[]},
						{key:'字段6',value:[]},
					],
				},
				rules: {
					wellId: {type: 'string',required: true},
				},
			}
		},

methods: {
    addItem(){
			  this.userForm.constructProcessList.push({
			    key: '',
			    value: []
			  })
			},
			deleteItem(item, index){
			  this.userForm.constructProcessList.splice(index, 1)
			},
			// 删除图片
			deletePic(index,i) {
				uni.showModal({
					content: "是否删除此图片?",
					success: (e) => {
						if (e.confirm) {
							this.userForm.constructProcessList[index].value.splice(i, 1);
						}
					}
				})
			},
    chooseImage: async function(i) {
				let _self = this;
				if (_self.userForm.constructProcessList[i].value.length >= 9) {
					let isContinue = await this.isFullImg(i);
					if (!isContinue) {
						return;
					}
				}				
				uni.chooseImage({
					sourceType: sourceType[this.sourceTypeIndex],
					sizeType: sizeType[this.sizeTypeIndex],
					count: 9,
					success: (res) => {	
						let tempFiles = res.tempFiles;
						let paths = tempFiles.map(file => file.path); // 提取路径					
						_self.userForm.constructProcessList[i].value = _self.userForm.constructProcessList[i].value.concat(paths);					
						
						// 发起上传图片的请求,将图片上传到服务器	
						//多图上传
						const pList = [];
						tempFiles.forEach(function(tempFile,item) {
							const p = new Promise(function (resolve, reject) {
								uni.uploadFile({
									url: _self.$api.baseUrl + "/nkdxsjcj/sys/base/uploadFiles",
									filePath: tempFile.path, 
									name: 'files',
									header: {'token': uni.getStorageSync('token')},
									formData: {
										'files': tempFile.path,
										folderName: _self.userForm.wellId
									},
									success: function (resl) {
										const data = JSON.parse(resl.data);
										resolve(data);
									},
									fail: function (err) {
										uni.showToast({
										    title: "上传失败:"+err,
										    icon: 'none',
										    duration: 2000
										});
										reject(err);
									}
								});
							});
							pList.push(p);
						});
						Promise.all(pList).then(function (results) {
							let fileList=[];
							for(let j=0; j<results.length;j++){
								fileList.push(results[j].data.toString())
							}
							_self.userForm.constructProcessList[i].value.concat(fileList);
							console.log('上传结束:');
						}).catch(function (err) {
							uni.showToast({
							    title: "上传失败:"+err,
							    icon: 'none',
							    duration: 2000
							});
							return
						});				
					},
					complete:(resp)=>{
						let resSize = resp.tempFiles[0].size;
						if(resSize > 20971520){
						    uni.showToast({
						        title: "上传的图片大小不超过20m",
						        icon: 'none',
						        duration: 2000
						    });
							return
						}
					}
				})
			},
isFullImg(i) {
				let _self = this;
				return new Promise((res) => {
					uni.showModal({
						content: "已经有9张图片了,是否清空现有图片?",
						success: (e) => {
							if (e.confirm) {
								_self.userForm.constructProcessList[i].value=[];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			previewImage(e,i) {
				console.log(e)
				var current = e.target.dataset.src;				
				uni.previewImage({
					current: current,
					urls: this.userForm.constructProcessList[i].value
				})
			},
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值