同时提交图片+表单
预期提交的表单如下图所示:
通过前面的学习,可以容易得到的思路是:首先将图片上传到服务器,获得其URL后,再和表单信息一起提交到预期的接口即可。
但是这里会出现一个问题,在调用uploadImage
后,虽然通过服务器的返回值我们可以得到永久的image URL,但是由于微信小程序中wx.uploadFile
并不是同步传送数据的,在进一步提交含有表单+image URL的 POST请求时,使用wx.request
接口不能获取到我们的image URL,提交到服务器上的图片路径为空。所以我们需要引入promise
:
uploadImage:function() {
var that = this;
const promise=new Promise((resolve)=> {
wx.uploadFile({
url: '图片接收接口',
filePath: that.data.img_path,
name: 'content',
header: {
"Content-Type": "multipart/form-data"
},
success: function (res) {
var data = JSON.parse(res.data);
that.setData({
url: (JSON.parse(res.data)).path,
})
resolve();
}
})
})
return promise;
},
然后再进行表单的提交时,使用then
:
formSubmit: function (e) {
this.uploadImage().then(()=> {
var that = this;
var temp = e.detail.value;
wx.request({
url: '接受表单的接口',
// 这里的data格式与服务器接口需求一致
data: { name: temp.name, food_class: temp.type, price: temp.price, detail: temp.detail, image_path: that.data.url },
// 提交表单使用POST,同时注意header的不再是默认的"application/json"
method: 'POST',
header: {
"content-type": "application/x-www-form-urlencoded"
},
success: function (res) {
wx.showToast({
title: '添加成功!',
icon: 'success',
duration: 2000
})
},
fail: function (res) {
console.log(res);
}
})
typelist.push(item);
this.setData({
[key]: typelist,
}),
})
},
这样就可以将图片提交时我们接收到的返回值再次用于表单的提交中。