1、引入vant weapp上传图片组件
将vant组件放置在小程序文件中,在小程序app.json文件usingComponents中引入上传图片组件地址,将下面代码放入usingComponents中,要注意文件地址是否正确。
"van-uploader": "@vant/weapp/uploader/index"
2、wxml页面展示上传组件
fileList 展示图片的url地址,格式为fileList: [ { url: 'https://img.yzcdn.cn/vant/leaf.jpg', name: '图片1' }]
afterRead是点击上传选择图片后读取的文件信息函数。
3、bind:after-read上传图片后执行函数
// 上传图片
uploadToCloud(file) {
const { file } = this.file;
console.log(file);//返回的图片临时地址
}
4、使用微信小程序api上传图片至服务器
wx.uploadFile({
url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
filePath: file,
name: 'file',
success (res){
const data = res.data //do something
}
})
将第三步中返回的图片临时地址通过wx.uploadFile api上传到服务器,filePath填入返回的图片地址,上传成功后通过success中的res返回,返回成功后对fileList赋值即可,并将返回成功图片地址储存到表单中,用于下一步的提交使用。
wx.uploadFile api详细使用方法可参考微信小程序api:https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html