Wechat does not support uploading multiple pictures at the same time, so how to gracefully upload multiple pictures at one time?

Just enter with the scene:

Comments on commodity orders can be made on multiple commodities at a time, and pictures and videos can be uploaded for each commodity. How to put these requirements together for unified processing?

  • goods

    • content
    • Pictures (need to upload first to obtain the temporary address of the server, you can upload more than one)
    • Video (need to upload the server to obtain the temporary address, can only be one video)
  • goods

    • content
    • The picture
    • video
  • goods

    • content
    • The picture
    • video
  • Submit data

Let’s see a good show:

// Submit comment data
submitAction(){

    // Create the request queue array
    var promiseAll = [];
    // Check whether the order has been commented and added to the queue
    for (let index = 0; index < this.data.commentModels.length; index++) {
       // Assemble the request queue
      let request = this.requestUploadData(index)
      promiseAll.push(request)
    }
    Promise.all(promiseAll).then((res) = >{
      // All requests are completed
      console.log('Over!! ')
      setTimeout(() = > {
        wx.navigateBack()
      }, 1500);
      wx.showToast({
        title: 'Comments submitted',}})}),// This is the comment content + picture + video of a single product
  requestUploadData(index) {

    let sectionVideos = this.data.sectionVideos
    let sectionUploadImages = this.data.sectionUploadImages

    const comment = this.data.commentModels[index];
    var promiseAll = [];
    if (sectionVideos[index]) { / / have a video
    // Upload video, obtain the temporary server video address after success, used to comment the video parameters of the submission interface
      let request = requestPromise({
        url: API.uploadFile,
        filePaths: [sectionVideos[index]],
        fileNames: ['multipartFile'].data: {
          type: 6
        }
      })
      promiseAll.push(request)
    }
    / / a picture
    let uploadImages = sectionUploadImages[index]
    if (uploadImages && uploadImages.length > 0) {
      let names = uploadImages.map((v) = >{return 'multipartFile'});
      // Images are similar to videos
      let request = requestPromise({
        url: API.uploadFile,
        filePaths: uploadImages,
        fileNames: names,
        data: {
          type: 3
        }
      })
      promiseAll.push(request)
    }

    // Assemble the data into a promise
    return Promise.all(promiseAll).then(res= > {
      vardata = { ... comment } res.forEach((v, i) = > {
        if (sectionVideos.length > 0 && i == 0) {
          // There is a video path
          data['video'] = v[0]}else {
          // Image path
          if (sectionVideos.length > 0) {
            // Have video cover
            data['videoImage'] = v.shift()['imagePath']
          }
          data['picturesList'] = v.map((value) = >value.imagePath)
          
        }
      })
     
      // Submit single data
      return requestPromise({
        url: API.orderComment,
        method: 'POST'.data: data,
        header: {'Content-Type':'application/json'}})})},Copy the code

If you look at it for the first time, you’ll see a lot of nesting, and it’s a little foggy. So LET me make a simple statement

RequestPromise: this is a wrapped data request class, including image upload, multiple image upload, actually called wx.uploadFile

All requests are assembled into a Promise to make a unified one-time request.

If you understand how Promise is used, add promise.all. It’s not hard to see how this is written.

The wrapper code for requestPromise is as follows

let ajaxTimes = 0;
/** Use mode: * requestPromise({url:'url', // required data:data, filePaths:[], fileNames:[], header:[:], method:'GET', hiddenLoading:false, Success: (orgRes) = > {/ / receiving here is that the original data}}), then ((result) = > {/ / here is receiving the data. The data of data}). The catch ((error) = > {}) * * /
function requestPromise(params) {

  // Check whether /my/ is a private path with a header token
  varheader = { ... params.header };varbuild = buildRequestHeader() header = { ... build, ... header } ajaxTimes++;// Display the loading effect
  if(! params.hiddenLoading) { wx.showLoading({title: "Loading".mask: true
    });
  }

  // Define the public URL
  const baseUrl = getApp().globalData.httpHost;

  return new Promise((resolve, reject) = > {

    var url = baseUrl + 'shop/' + params.url

    // Upload the file
    if (params.filePaths && params.filePaths.length > 0) {
      // Upload a file
      var index = 0
      var respDatas = []
      function uploadImage(filePaths) {
        wx.uploadFile({
          filePath: filePaths[index],
          name:  params.fileNames ? params.fileNames[index] : 'file'.formData: params.data,
          header: header,
          url: url,
          success (res){
            let jsonData = JSON.parse(res.data)
            const data = jsonData.data
            respDatas.push(data)
            index += 1
            if (index == params.filePaths.length) {
              resolve(respDatas);
              // Close the waiting icon
              ajaxTimes--;
              if (ajaxTimes === 0) {
                // Close the waiting icon
                wx.hideLoading();
              }
              return;// It has been uploaded
            }
            uploadImage(filePaths)
          }
        })
      }
      uploadImage(params.filePaths)


      return;
    }
    // The file is uploadedwx.request({ ... params,header: header,
      url: url,
      success: (result) = > {
        if (result.data.code == 200) {
          resolve(result.data.data);
          if (params && params.success) {
            params.success(result.data);
          }
          // The code will be blocked
          analysisResponseHeader(result.header)
        } else if (result.data.code == 205) {
          // If not logged in, you need to log in again
          reject(result.data.msg);

          let pages = getCurrentPages();
          let page = pages.pop().route;
          console.log(page)
          if(page ! ='pages/loginphone/index') {
            wx.navigateTo({
              url: '/pages/loginphone/index'})},// Clear user information
          wx.setStorageSync('serverIsLogin'.false)
          getApp().globalData.wxLoginCode = null

        } else {
          reject(result.data.msg);
          var msg = result.data.msg ?? "";
          if (msg.length > 6) {
            if (msg.length > 100) {
              msg = msg.substring(0.100) + "...";
            }
            wx.showModal({
              title: msg,
              showCancel:false})},else {
            wx.showToast({
              title: msg,
            })
          }
        }
      },
      fail: (err) = > {
        reject(err.errMsg);
      },
      complete: () = > {
        ajaxTimes--;
        if (ajaxTimes === 0) {
          // Close the waiting iconwx.hideLoading(); }}}); })}// parse the response header to update the user sessionId
function analysisResponseHeader(header) {
  var cookie = header["Cookie"]
  if(! cookie) { cookie = header["Set-Cookie"]}if (cookie && cookie.indexOf("sessionId=") > =0) {
    cookie = cookie.replace('sessionId='.' ')
    var iv = header["iv"]
    var sessionId = signature.decrypt(cookie, iv)
    if (sessionId) {
      wx.setStorageSync('user_sessionId', sessionId)
    }
  }
}

// Assemble the request header information
function buildRequestHeader() {
  var header = {}
  header["mini-version"] = getApp().globalData.mini_version
  header["Content-Type"] = "application/x-www-form-urlencoded"
  // User-Agent
  var iv = signature.getIVTimestamp()
  var sessionId = wx.getStorageSync('user_sessionId')
  if (sessionId) {
    var cookie = signature.encrypt(sessionId, iv)
    header["Cookie"] = "sessionId=" + cookie
    header["iv"] = iv
  }
  return header
}


Copy the code