一、需求说明
- 可选取相册照片,可拍照
- 可选择压缩大小,可选择原图大小
- 每次最多可选择 5 张图片
二、需求实现
2.1 选取照片实现
通过调用小程序 api - chooseImage 来实现选取照片功能
1 2 3 4 5 6 7 8 9 10
| // 定义一个变量,用来存储用户选取的图片路径 let imagePaths wx.chooseImage({ count: 5, // 限制每次最多选择 5 张 sizeType: ['original', 'compressed'], // 可选择压缩大小,可选择原图大小 sourceType: ['album', 'camera'], // 可选取相册照片,可拍照 success: res => { // 选取图片成功的回调函数 imagePaths = res.tempFilePaths // 存储选取的图片路径,是个数组 } })
|
2.2 上传照片实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| // 定义一个变量,用来存储上传成功的图片路径 let successPaths = [] // wx.uploadFile 接口只能一次上传 1 张图片,所以需要先遍历 imagePaths.forEach((path) => { wx.uploadFile({ url: api.apiRootUrl + '/distribution/addPicture', // 接口地址 filePath: path, // 当前图片路径 name: 'file', header: { "Content-Type": "multipart/form-data" }, success: res => { // 上传成功的回调函数 if (res.code == 200) { successPaths.push(res.filePath) } else { this.showToast({ title: res.msg }) } let filePaths = `formData.filePaths` // 存储上传成功的图片路径 this.setData({ [filePaths]: successPaths }) } }) })
|
2.3 图片预览实现
1 2 3
| <view wx:for="{{formData.filePaths}}" wx:key="filePath"> <image src="{{filePath}}"></image> </view>
|