微信小程序-處理多個文件上傳

一、方法的封裝


/**
  * 採用遞歸的方式上傳多個文件
  * filePaths 要上傳的資源
  * results 上傳成功返回的數據
  * successUp 成功個數
  * failUp 失敗個數
  * index 上傳文件的下標
  */
function uploadOneByOne(filePaths = [], results = [] , successUp = 0, failUp = 0, index = 0) {
  return new Promise((resolve, reject) => {

    if (filePaths.length == 0) {
      resolve(results)
    }

    wx.showLoading({
      title: `正在上傳第${index + 1}個`,
    })
    wx.uploadFile({
      url: "https://xxxx.xxx.com/auth/file/upload",//服務器地址
      filePath: filePaths[index],
      name: "file",//對應字段名
      header: { "content-type": "application/json; multipart/form-data;" },
      success: res => {
        successUp++;
        if (res.data) {
          results = results.concat(JSON.parse(res.data));
        }
      },
      fail: res => {
        failUp++;
      },
      complete: res => {
        index++;
        if (index >= filePaths.length) {
          wx.hideLoading();
          console.log('上傳成功' + successUp + ',' + '失敗' + failUp);
          resolve(results);
        } else {
          uploadOneByOne(filePaths, results, successUp, failUp, index).then(res => {
            resolve(res);
          });
        }
      }
    })
  })
}

二、使用

// 上傳圖片
if (this.data.chooseImg.length > 0) {
    var that = this;
    that.uploadOneByOne(that.data.chooseImg).then(res => {
        var urls = res.map(item => {
            return `/resource/${item.group}/${item.path}`
        })
        console.log(urls);
    })
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章