1. 定义一个通用的js
/* 函数描述:作为上传文件时递归上传的函数体体;
* 参数描述:
* url是上传地址
* filePaths是文件路径数组
* requestHeader是头部
* fileParams是参数
* successUp是成功上传的个数->0
* failUp是上传失败的个数->0
* count是文件路径数组的指标->0
* length是文件路径数组的长度
*/
function djUploadImgs(url, filePaths, requestHeader, fileParams, successUp, failUp, count, length, onSuccess, onFail, onAfail){
var that = this;
wx.uploadFile({
url: url,
filePath: filePaths[count],
header: requestHeader,
name: 'file',
formData: fileParams,
success: function (res) {
var jsonDict = JSON.parse(res.data);
console.log('====', jsonDict);
if (res.statusCode == 200) {
successUp++;
onSuccess(jsonDict);
}
else{
onFail(jsonDict);
}
},
fail: function (res) {
failUp++;
onAfail(res.data);
},
complete: function () {
count++;
if (count == length) { //上传完毕
console.log('总共' + successUp + '张上传成功,' + failUp + '张上传失败!');
}
else { //递归调用djUploadImgs函数
that.djUploadImgs(url, filePaths, requestHeader, fileParams, successUp, failUp, count, length, onSuccess, onFail, onAfail);
}
}
})
}
2. 使用
var url = "你要上传的url";
var headers = {"content-type": "multipart/form-data"};
var paramData = {}; //上传参数
var tempFilePaths = that.data.uploadImages; //选择好的图片
var successUp = 0; //成功
var failUp = 0; //失败
var length = tempFilePaths.length; //总数
var count = 0; //第几张
//调用已经写好的
that.djUploadImgs(url, tempFilePaths, headers, paramData, successUp, failUp, count, length, function (successDict){
},
function (failDict) {
},
function (errorDict){
})