需要掌握的知识有:
- promise 方法
- 微信小程序开发的 俩个API接口调用 wx.chooseImage(Object object)、 wx.uploadFile(Object object)
详情代码
//图片选择 展示图片但不上传
chooseImage(e) { const that = this wx.chooseImage({ count: 9, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: res => { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 // this.setData({ // show: true // }) const tempFilePaths = res.tempFilePaths console.log(res) this.setData({ imageList: this.data.imageList.concat(res.tempFilePaths) }) // const imglist = [] } }) },
//接下来执行异步
async formSubmit(e) { if (!e.detail.value.input1) { wx.showToast({ title: '请填写反馈内容', icon: 'none', duration: 2000 }) return } if (this.data.imageList.length) { this.setData({ show: true }) let imgs = this.data.imageList await this.uploadimgs(imgs) // console.log('异步执行完成') } // console.log('最后打印', this.data.imageLists) const datas = { problem: e.detail.value.input1, image: this.data.imageLists.join(','), phone: e.detail.value.input } insertReportProblem(datas).then(res => { if (res.code == 0) { this.setData({ form_input1: '', form_input: '', wordnum: 0, imageList: [], imageList: [] }) wx.showToast({ title: '发送成功', icon: 'success', duration: 2000 }) } else { wx.showToast({ title: '发送失败', icon: 'success', duration: 2000 }) } }) }, uploadimgs(imgs) { const imglist = [] const that = this return new Promise((reslove, reject) => { imgs.map(item => { wx.uploadFile({ url: 'http://hdsjfjds.fsdf.fsdfs...', //图片上传接口地址 filePath: item, name: 'file', header: { 'Content-Type': 'multipart/form-data', accept: 'application/json' }, formData: { file_source: 'miniProgram' }, success: function (res) { const datas = JSON.parse(res.data) imglist.push(datas.data.img_url) if (imglist.length === imgs.length) { that.setData({ imageLists: that.data.imageLists.concat(imglist), show: false }) reslove() } }, fail: function (res) { // console.log(res) } }) }) }) },