1 首先,添加上传按钮
<van-button type="default" bindtap="uploadImg">上传图片
2 添加uploadImg方法
/** * 页面的初始数据 */ data: { detail: {}, content: '', //评价的内容, score: 5, //当前评价的分数 images: [], //上传的图片 fileIds: [], //上传的图片的云存储的id movieId: -1 },
uploadImg: function(event) { //选择图片 wx.chooseImage({ count: 9, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: res => { // tempFilePath可以作为img标签的src属性显示图片 const tempFilePaths = res.tempFilePaths; //console.log(tempFilePaths); this.setData({ //取到当前图片的images 然后拼接起来,如果直接赋值 会覆盖掉 images: this.data.images.concat(tempFilePaths) }); } }) },
3 把上传的图片循环显示出来
<view> <image class="comment-img" wx:for="{{images}}" wx:key="{{index}}" src="{{item}}" > </image> </view>
/* pages/comment/comment.wxss */ .comment-img{ width: 200rpx; height: 200rpx; margin-right: 20rpx; }
<--------已上传的图片
4 上传到云存储,然后云存储返回fileid
submit: function() { wx.showLoading({ title: '评论上传中。。', }) console.log(this.data.content); //评价 console.log(this.data.score); //评分 //上传图片到云存储 let promiseArr = []; //循环遍历上传的图片 for (let i = 0; i < this.data.images.length; i++) { promiseArr.push(new Promise((reslove, reject) => { let item = this.data.images[i]; let suffix = /.w+$/.exec(item)[0]; //正则表达式,返回文件的扩展名 wx.cloud.uploadFile({ cloudPath: new Date().getTime() + suffix, //上传至云端的路径 filePath: item, // 小程序临时文件路径 success: res => { // get resource ID console.log(res.fileID) this.setData({ fileIds: this.data.fileIds.concat(res.fileID) }); reslove(); }, fail: err => { // handle error } }) })) } Promise.all(promiseArr).then(res => { //插入数据 db.collection('comment').add({ data: { content: this.data.content, score: this.data.score, movieid: this.data.movieId, fileIds: this.data.fileIds } }).then(res => { wx.hideLoading(); wx.showToast({ title: '评价成功', }) }).catch(err => { console.log(err); wx.hideLoading(); wx.showToast({ title: '评价失败', icon: 'none', }) }) }); },