微信小程序图片上传默认是异步的形式,主要用到wx.uploadFile(Object object),将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求。也就是下面的示例代码
wx.chooseImage({ success (res) { const tempFilePaths = res.tempFilePaths wx.uploadFile({ url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址 filePath: tempFilePaths[0], name: 'file', formData: { 'user': 'test' }, success (res){ const data = res.data //do something } }) } })
但是我有时需要把它改成同步的,可以改成如下形式:
1、图片上传方法:
//图片上传 uploadimg:function(path){ return new Promise((resolve, reject) =>{ wx.uploadFile({ filePath: path, name: 'file', url: 'https://www.tpxhm.com/photo', success(res) { //resolve作用提示小程序请求已结束 resolve(JSON.parse(res.data)) }, fail (err) { reject(err) } }); }); },
2、使用方法:
async formSubmit(e) { var _that2=this let images = _that2.data.pics // console.log(_that2.data.pics) var _images = []; for (let i = 0; i < images.length; i++) { var res = await _that2.uploadimg(images[i]) _images[i] = res.data } console.log(_images) }
详细示例:
// index.js // 获取应用实例 const app = getApp() Page({ data: { pics: [],//图片 }, onLoad() { }, //图片上传 uploadimg:function(path){ return new Promise((resolve, reject) =>{ wx.uploadFile({ filePath: path, name: 'file', url: 'https://www.tpxhm.com/photo', success(res) { //resolve作用提示小程序请求已结束 resolve(JSON.parse(res.data)) }, fail (err) { reject(err) } }); }); }, async formSubmit(e) { var _that2=this let images = _that2.data.pics // console.log(_that2.data.pics) var _images = []; for (let i = 0; i < images.length; i++) { var res = await _that2.uploadimg(images[i]) _images[i] = res.data } console.log(_images) } })
文章评论(0)