微信小程序官网社区有申明微信小程序无法多文件上传,所以要通过递归进行多文件上传。
网上得上传例子都不满足我的要求,如下是我的代码,希望能给予参考。
方法upload单文件上传 方法uploadFils多文件上传
export function uploadFils(url, filePathArr) {
return uploadFilsSync(url, filePathArr, 0, { success: [], fail: [] });
}
function uploadFilsSync(url, filePathArr, index, result) {
return upload(url, filePathArr[index++], {})
.then(res => {
result.success.push({ index: index, res: res });
if (index === filePathArr.length) {
return result;
} else {
return uploadFilsSync(url, filePathArr, index, result);
}
})
.catch(err => {
result.fail.push({ index: index, res: err });
if (index === filePathArr.length) {
return result;
} else {
return uploadFilsSync(url, filePathArr, index, result);
}
});
}
export function upload(url, filePath, formData = {}) {
let header = { "Content-Type": "multipart/form-data" };
return new Promise((resolve, reject) => {
wx.uploadFile({
url: config.server + url,
header: header,
filePath: filePath,
name: "file",
formData: formData,
success(res) {
resolve(res.data);
},
fail: function(error) {
reject(error);
}
});
});
}
返回结果:
index:第几个上传文件,res做为上传结果
{
"success":[
{
"index":1,
"res":{
"data":"123"
}
}
],
"fail":[
]
}