uniapp单文件and多文件上传功能

本文介绍了如何在uniapp中使用单文件上传功能处理留言,并探讨了单次上传与批量上传的区别。作者展示了两种方法:单文件上传的逐个完成回调和多文件上传的使用示例,重点在于处理小程序限制及解决上传策略。

一、上传文件功能

前端上传后界面后,点击 确定 按钮,上传至后台。

uniapp拍照上传功能

二、代码

<view class="top-nav-c">
	<view class="before" @tap="isShowDoMessage = false">取消</view>
	留言板
	<view class="after" :class="{'submit-ck': isSubmit}" @tap="onSubmitMessageClick">确定</view>
</view>

该方式属于单文件上传,由于小程序上传文件不能多文件上传

只能通过 complete 回调,继续上传下一个图片资源
还有一种遍历所有图片资源,一一上传图片的做法
let i = 0 // 写在 export default { 上面
onSubmitMessageClick() {
	/*
	 * 前端交互,非上传文件
	if (this.textarea === '') { // 提交内容不能为空
		uni.showToast({
			title: '提交内容不能为空~'
		})
		return false
	}
	*/
	
	this.doUploadImg()
},
// 上传图片--后台
doUploadImg() {
	const _this = this
	const len = this.imageList.length
	
	/* 上传图片 */
	uni.uploadFile({
		  url : uploadUrl,
		  filePath: this.imageList[i], // 单文件上传方式
		  name: 'uploadFile', // 单文件上传方式
		  header:{
			  // "Content-Type": "multipart/form-data"
		  },
		  formData: { // 后台需要的除图片外的其他参数
			  picType: 501,
			  parentId: _this.parentId,
			  openId: _this.openId ? _this.openId : GetStorage('openId')
		  },
		  success: function (res) {
			  if (res.data === 'wrong') {
				  uni.showToast({
				  	title: '上传图片失败'
				  })
			  }
		  },
		  complete: function () {
			  i++
			  if (i === len) {
				  uni.showToast({
					  title: '上传图片成功!'
				  })
			  } else {
				  _this.doUploadImg()
			  }
		  },
		  error: function (res) {
			console.error(res, 'res---error')
		  }
	})
},

H5端的多文件上传

// 上传图片--后台
doUploadImg() {
	const _this = this
	
	const tempImg = _this.imageList.map(item => {
		return {
			name: 'uploadFile',
			uri: item
		}
	})
	/* 上传图片 */
	uni.uploadFile({
		  url : uploadUrl,
		  files: tempImg,  // 多文件上传方式
		  header:{
			  // "Content-Type": "multipart/form-data"
		  },
		  formData: { // 后台需要的除图片外的其他参数
			  picType: 501,
			  parentId: _this.parentId,
			  openId: _this.openId ? _this.openId : GetStorage('openId')
		  },
		  success: function (res) {
			  if (res.data === 'wrong') {
				  uni.showToast({
				  	title: '上传图片失败'
				  })
			  }
		  },
		  error: function (res) {
			console.error(res, 'res---error')
		  }
	});
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值