上传作品图片,上传头像(count=1),亲测有效
分享一下核心代码,希望能帮助大家
1.wxml
<!-- 上传作品 --><view class='upload-works' style='height:{{screenHeight}}px' wx:if="{{isUpWork}}"><view class='work-box'><view class='works-tit'>图片上传:</view><view class='works-img'><view class="img" wx:for="{{worksImgs}}" wx:for-item="item" wx:key="*this"><!-- 图片缩略图 --><image src="{{item}}" mode="aspectFill"></image><!-- 移除图片的按钮 --><view class="delete-btn" data-index="{{index}}" catchtap="deleteImg">删除</view></view><view class='img iconfont icontianjia' wx:if="{{worksImgs.length<9}}" bindtap="chooseImage"></view></view></view><!-- 按钮 --><view class='btns'><button class='cancle' catchtap='cancleWorks'>取消</button><button class='submit' catchtap='submitWorks'>提交</button></view></view>
2.js
chooseImage: function () {let that = this;let worksImgs = that.data.worksImgs;let len = that.data.worksImgs.length;wx.chooseImage({count: 9 - len, //最多选择9张图片sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有success: function (res) {console.log(res);// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片if (res.tempFilePaths.count == 0) {return;}let tempFilePaths = res.tempFilePaths;// let token = app.data.uptoken;//上传图片 循环提交for (let i = 0; i < tempFilePaths.length; i++) {wx.uploadFile({url: 'url', //此处换上你的接口地址 filePath: tempFilePaths[i],name: 'upload_file',header: {"Content-Type": "multipart/form-data",'accept': 'application/json',},success: function (res) {console.log(res);let data = JSON.parse(res.data); // 这个很关键worksImgs.push(data.data.url);that.setData({worksImgs: worksImgs})}})}}})},// 删除上传的图片deleteImg: function (e) {var worksImgs = this.data.worksImgs;var itemIndex = e.currentTarget.dataset.index;worksImgs.splice(itemIndex, 1);this.setData({worksImgs: worksImgs})},// 提交个人作品submitWorks:function(){let that = this;let worksImgs = String(that.data.worksImgs);let obj = {store_id: that.data.store_id,mode_id: that.data.mode_id,works_img: worksImgs,works_info: that.data.works_info, is_xs : 1}if (obj.works_img.length == 0 || obj.works_info == ''){wx.showModal({title: '提示',content: '数据不能为空!',showCancel: false,})}else{utils.postRequest('Mode/worksAdd', obj, '加载中', (res) => {if (res.data.rc == 200) {wx.showModal({title: '提示',content: '作品上传成功',showCancel: false,success: function (res) {if (res.confirm) {that.setData({isUpWork: false})that.onShow();}}})} else {wx.showModal({title: '提示',content: '作品上传失败',showCancel: false,success: function (res) {if (res.confirm) {that.setData({isUpWork: false})that.onShow();}}})}})}},
注意:微信公众平台小程序,开发栏目uploadFile合法域名,一定要配置图片保存的域名,例如:七牛云等等