一、上传文件功能
前端上传后界面后,点击 确定 按钮,上传至后台。
二、代码
<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')
}
});
},