微信小程序选择本地图片或者相机拍照并上传服务器需要用到以下两个方法:
1.wx.chooseImage(Object object)
从本地相册选择图片或使用相机拍照
2.wx.uploadFile(Object object)
将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data
chooseImg() {const that = this;wx.chooseImage({count: 6,sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有success (res) {// tempFilePath可以作为img标签的src属性显示图片const tempFilePaths = res.tempFilePathsfor (let i = 0; i < tempFilePaths.length; i += 1) {wx.uploadFile({url: 'https://example./upload', //仅为示例,非真实的接口地址filePath: tempFilePaths[i],name: 'file',header: {// 我的 HTTP 请求中需要token,视情况而定是否需要headertoken: wx.getStorageSync('token') || '',},formData: {// HTTP 请求中其他额外的 form datafile: tempFilePaths[i],},success (res){console.log(res);// 上传成功后相关操作},fail() {wx.showToast({title: '上传失败,请重试', //弹框内容icon: 'fail', //弹框模式duration: 2000 //弹框显示时间}) },})}},})},
避坑: 在项目转测后,发现选择图片之后不显示,但是使用调式模式时,就能显示,后来发现是使用uploadFile方法前,需要在小程序后台配置uploadFile的合法域名,配完后即可正常选择图片上传