效果:
小程序上传函数 wx.uploadFile(Object object)应该是用了线程发送的,如果遍历上传的话获取到路径后遍历上传的话,会出现异常,因为上传状态没法获取到后台返回的结果
arr是要上传的图片路径数组,arr数组结构为:
[{upload_status: 0, path: "http://tmp/wxa1fd91bd32bf7481.o6zAJswDOgl7nijr8CZf….sUPpf8epWNsZ53771955908686b17d4e2ac93d9a51c9.png"},
{upload_status: 0, path: "http://tmp/wxa1fd91bd32bf7481.o6zAJswDOgl7nijr8CZf….gJWRzXilmRebd35abde6fe5e4b1e5adb6bc73c0a9797.png"}]
src_json结构
var src_json: {
src_comp: [],
src_door: [],
src_business: [],
src_doc: any[],
src_product: [],
src_other: []
}
下面是用for遍历图片数组上传,在上传成功后success函数中修改upload_status状态,但是很遗憾,小程序上传用的是线程发送,这个状态没法改变,因为i会变了,不是对应哪个图片的i
upload: function (key,that,arr, photoType){
console.log("进入上传函数")
console.log(arr)
var len = arr.length
for (var i = 0; i < len; i++) { //遍历数组,上传图片
console.log("遍历")
var upload_task = wx.uploadFile({ //发送上传请求
url: url + '/survey/' + taskId + "/" + photoType + '/photo',
filePath: arr[i].path,
name: "file",
header: {
"content-type": "multipart/form-data",
"authorization": da.data.sessionId
},
success: function (res) {
console.log("上传成功")
console.log(res.data)
var data = JSON.parse(res.data) //转化成json
console.log(data)
if (data.status == true) {//后台返回的上传成功状态
console.log("jin")
console.log(i)
src_json[key][i].upload_status = 1 //更改当前图片的状态为已上传
}
},
fail: (res) => {
console.log("上传失败")
console.log(res.data)
// stat = 0;
},
complete:function(res){
}
})
}
},
这种怎么解决?应该用递归调用函数来解决这个问题,下面是递归函数写法替换for循环:
//index是数组下标索引只,一开始传入是0
//
upload: function(key, index, that, arr, photoType) {
console.log("进入上传函数")
console.log(arr)
var len = arr.length
var upload_task = wx.uploadFile({ //发送上传请求
url: url + '/survey/' + taskId + "/" + photoType + '/photo',
filePath: arr[index].path,
name: "file",
header: {
"content-type": "multipart/form-data",
"authorization": da.data.sessionId
},
success: function(res) {
console.log("上传成功")
console.log(res.data)
var data = JSON.parse(res.data)
console.log(data)
if (data.status == true) {
console.log("jin")
src_json["src_" + key][index].upload_status = 1
switch (key) { //下面代码是实时更新了图片状态的,每上传一片,就更新一次data的值,这样前端显示图片状态就会改变
case "comp":
that.setData({
src_comp: src_json["src_" + key]
})
break
case "door":
that.setData({
src_door: src_json["src_" + key]
})
break
case "business":
that.setData({
src_business: src_json["src_" + key]
})
break
case "doc":
that.setData({
src_doc: src_json["src_" + key]
})
break
case "product":
that.setData({
src_product: src_json["src_" + key]
})
break
case "other":
that.setData({
src_other: src_json["src_" + key]
})
break
}
index++;
console.log(index)
}
},
fail: (res) => {
console.log("上传失败")
console.log(res.data)
// stat = 0;
},
complete: function(res) {//解决循环问题,这里递归调用
if (index == len) {//当下标索引等于长度,停止递归调用
console.log(index)
wx.showToast({
title: '上传完成',
icon: 'success',
duration: 2000
})
} else {
console.log("长度小于数组长度")
console.log('正在上传第' + index + '张');
that.upload(key, index, that, arr, photoType) //递归
}
}
})
}
上传函数的调用:
that.upload("business", 0, that, up, photoType)
|
请发表评论