<!--pages/test/test.wxml-->
<view>
<view bindtap="upImg">上传</view>
</view>
// test.js
const maxUpImgs = 9 //单次上传数量1-9
let upCpImg = [] //待上传数组
Page({
data: {
},
//上传文件至微信服务器
upImg: function () {
const _this = this
if (upCpImg.length >= maxUpImgs) {
return wx.showToast({
title: `最大数量不能超过${maxUpImgs}`,
icon: 'none',
duration: 2000
})
}
wx.chooseImage({
count: maxUpImgs,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var tempFilePaths = res.tempFilePaths
_this.up2Server(tempFilePaths)
}
})
},
// 通过方上传法获取返回数据
async up2Server(tempFilePaths) {
const _this = this
let imageData = await _this.upload(tempFilePaths)
console.log(imageData)
},
// 上传到本地服务器
upload: (pathArr) => {
wx.showToast({
icon: "loading",
title: "正在上传"
})
let index = 0 //当前上传数量
const maxlength = pathArr.length//总上传数量
let success = 0 //成功数量
let fail = 0 //错误数量
let outArr = []//数据库返回数据的地址
let outArrShow = []//微信上传图片的地址 *当url返回数据为相对路径时使用,反之可无视
return new Promise(function (resolve, reject) {
const up = () => {
wx.showToast({
icon: "loading",
title: `正在上传(${index + 1}/${maxlength})`
})
wx.uploadFile({
url: "",//服务器URL
filePath: pathArr[index],
header: {
"Content-Type": "multipart/form-data"
},
formData: {
params: {} //其他相关参数
},
name: 'image',
success: (res) => {
var data = res.data//根据实际情况修改返回数据的URL
outArr.push(data)
outArrShow.push(pathArr[index])
success++
},
fail: (res) => {
fail++;//图片上传失败,图片上传失败的变量+1
},
complete: () => {
index++
if (index >= maxlength) { //当图片传完时,停止调用
const info = {
success: success,
fail: fail,
file: outArr,
fileShow: outArrShow
}
wx.hideToast()
resolve(info)
} else {
//若图片还没有传完,则继续调用函数
up();
}
}
});
}
up()
})
}
})