小程序端代码:
data:{
form.filePath
},
uploadFile(){
wx.chooseMessageFile({
count: 3,
type:'file',
success:async (res)=>{
wx.showLoading({title:'上传中...'})
var successUp = 0; //成功
var failUp = 0; //失败
var length = res.tempFiles.length; //总数
var count = 0; //第几张
var filePath = [];//存储每次上传文件的路径
this.uploadOneByOne(res.tempFiles,successUp,failUp,count,length,filePath);
wx.hideLoading({})
}
})
},
/**
* 采用递归的方式上传
*/
uploadOneByOne(imgPaths,successUp, failUp, count, length,filePath){
var that = this;
wx.showLoading({
title: '正在上传第'+count+'张',
})
wx.uploadFile({
url: `${app.globalData.httpHost}orderUpSingleImg`,
filePath: imgPaths[count].path,
name: 'ecode',
success:function(e){
//将文件路径中的\符号转为/符号
let fileName = JSON.parse(e.data).path.replace(/\\/g,'/');
fileName = 'http://localhost:3000/upload' + fileName;
filePath.push(fileName);
successUp++;//成功+1
},
fail:function(e){
failUp++;//失败+1
},
complete:function(e){
count++;//下一张
if(count == length){
//上传完毕,作一下提示
console.log('上传成功' + successUp + ',' + '失败' + failUp);
that.setData({
'form.filePath':filePath
})
wx.showToast({
title: '上传成功' + successUp,
icon: 'success',
duration: 2000
})
}else{
//递归调用,上传下一张
that.uploadOneByOne(imgPaths, successUp, failUp, count, length, filePath);
console.log('正在上传第' + count + '张');
}
}
})
},
node.js +express 后端API:
router.post('/orderUpSingleImg',upload.single('ecode'),(req,res)=>{
res.send(req.file)
})