前言
从去年开始接手小程序项目,想把开发过程中遇到的一些问题记录下来,方便日后使用,也想分享给大家,哈哈哈哈哈哈~~~
小程序开发过程中,遇到选择多个图片后上传的功能,使用wx.uploadFile(),一次只能上传一个文件,想要批量上传只能递归上传。
imageUpload.js (封装了一下,方便多处调用)
module.exports = {
imageRecursionUpload (tempFilePaths) {
//tempFilePaths为要上传文件资源的路径 (本地路径),数组类型
var promise = Promise.all(tempFilePaths.map((tempFilePath, index) => {
return new Promise(function (resolve, reject) {
wx.uploadFile({
url: fileUploadUrl, //fileUploadUrl文件上传接口
filePath: tempFilePath,
name: 'file',
header: {
"Authorization": wx.getStorageSync('token'), // 本项目要求必须携带token
"token": wx.getStorageSync('token'),
},
formData: {},
success: function (res) {
resolve(res.data);
},
fail: function (err) {
console.log(err)
reject(new Error('failed to upload file'));
}
});
});
}));
return promise
}
}
引用
import {imageRecursionUpload} from '../../../../utils/imageUpload'
wx.chooseImage({
count: 8,
sourceType: ['album', 'camera'],
success: function (res) {
// 调用图片上传接口
var promise = imageRecursionUpload(res.tempFilePaths)
promise.then(function (results) {
//返回上传成功的数据 results为数组类型
console.log(results)
}).catch(function (err) {
console.log(err);
});
}
})