小程序多图上传并返回操作

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

> 小程序上传图片及预览图片
> 小程序选择、预览、删除、上传图片

js:


1. /**
2.   * 上传图片
3.   */
4.  upImg: function (e) {
5.      let that = this
6.      wx.chooseImage({
7.          success: function (res) {
8.              // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
9.              let tempFilePaths = res.tempFilePaths
10.              // console.log(tempFilePaths)
11.              let imgs = that.data.imgs  // 这个是储存图片地址,用于显示图片
12.              let image = that.data.image  // 这个是获取图片名称或者id等后端发送请求需要的数据
13.              that.uploadImage(0, tempFilePaths)
14.          }
15.      })
16.  },
17.
18.  /**
19.   * 图片上传接口
20.   */
21.  uploadImage: function (i,filePath){
22.      if (i == filePath.length){
23.          return
24.      }
25.      let that = this
26.      let imgs = that.data.imgs
27.      let image = that.data.image
28.      wx.uploadFile({
29.          url: app.globalData.api + '/Uploads/uploader', //仅为示例,非真实的接口地址
30.          filePath: filePath[i],
31.          name: 'file',
32.          success: function (res) {
33.              let img = JSON.parse(res.data)
34.              console.log(img)
35.              if (img.code == 200) {
36.                  imgs.push(img.data.url_file_name)
37.                  image.push(img.data.file_name)
38.                  that.setData({
39.                      imgs,
40.                      image
41.                  })
42.                  console.log(that.data.imgs)
43.                  console.log(that.data.image)
44.                  i++
45.                  that.uploadImage(i, filePath)
46.              }
47.              //do something
48.          }
49.      })
50.  },