小程序多图上传服务器接收返回数据操作

时间:2022-07-27
本文章向大家介绍小程序多图上传服务器接收返回数据操作,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

之前有写过小程序上传图片的,大多数都是前端处理,这篇是关于上传到服务器接收返回数据操作的,这里使用迭代器防止数据返回异步。

js:

/**
  * 上传图片
  */
 upImg: function (e) {
     let that = this
     wx.chooseImage({
         success: function (res) {
             // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
             let tempFilePaths = res.tempFilePaths
             // console.log(tempFilePaths)
             let imgs = that.data.imgs  // 这个是储存图片地址,用于显示图片
             let image = that.data.image  // 这个是获取图片名称或者id等后端发送请求需要的数据
             that.uploadImage(0, tempFilePaths)
         }
     })
 },
 /**
  * 图片上传接口
  */
 uploadImage: function (i,filePath){
     if (i == filePath.length){
         return
     }
     let that = this
     let imgs = that.data.imgs
     let image = that.data.image
     wx.uploadFile({
         url: app.globalData.api + '/Uploads/uploader', //仅为示例,非真实的接口地址
         filePath: filePath[i],
         name: 'file',
         success: function (res) {
             let img = JSON.parse(res.data)
             console.log(img)
             if (img.code == 200) {
                 imgs.push(img.data.url_file_name)
                 image.push(img.data.file_name)
                 that.setData({
                     imgs,
                     image
                 })
                 console.log(that.data.imgs)
                 console.log(that.data.image)
                 i++
                 that.uploadImage(i, filePath)
             }
             //do something
         }
     })
 },