小程序开发之图片上传

2,291 阅读1分钟

一周时间,一个人写小程序页面,对接数据真心累!终于完工了,突然要加一个客户意见反馈,小生不才,自己设计了一个奇丑无比的页面,顺带上传图片功能,里面的坑太多了,希望对大家有帮助!



首先我们确定我们要用哪些API,一个是选择图片,另一个是上传图片

 1、wx.chooseImage({success: function(res) {},}) ;

       wx.uploadFile({url: '',filePath: '',name: '',});

   官方文档,描述的一清二楚我们需要传的参数,下面说一下我遇到的坑!

坑一:小程序支持es6的语法是不错的,但是当时需要赋值的时候,不能用箭头函数,不然报错!有图有真相!看到这个真刺激,研究了二小时,改回直接通了,我的内心是崩溃的。



坑二:filePath参数单图上传还好,你说是个字符串我还能理解,多图上传是不是要数组,如果你这样想是大错特错,还是字符串,你的内心崩溃吗?别害怕有大哥在!一个for循环搞定,你最多能传9就,那就遍历一下呗!相当于一个api执行9次,没办法只能这样了!

坑三:name参数,你打算传什么,看官方文档应该是file,老铁没毛病!文档就是这样写的,这个参数写的是你们后台给你规定的字符段,你传的key的参数名!

upload:function(e){    var that = this;    let arr = that.data.arr;    wx.chooseImage({      success: function (res) {        var tempFilePaths = res.tempFilePaths        that.setData({          tempFilePaths: tempFilePaths        })        for (let i = 0; i < that.data.tempFilePaths.length; i++) {          wx.uploadFile({            url:'https://test.heitouyang.cn/api/file/upload/product',            filePath: that.data.tempFilePaths[i],            name: 'file',            success: function (res) {              var fileUrl = that.data.fileUrl              fileUrl = 'https://test-api.heitouyang.cn/api/file/upload/product';              arr.push(fileUrl);              that.setData({                fileUrl: fileUrl,                arr: arr              })            }          })        }      },    })  },