wxml代码:
<view class="weui-uploader">
<view class="img-v weui-uploader__bd">
<view class='pic' wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
<image class='weui-uploader__img '
src="{{item}}"
data-index="{{index}}" mode="aspectFill" bindtap="previewImg">
<icon type='cancel' class="delete-btn" data-index="{{index}}" catchtap="deleteImg"></icon>
</image>
</view>
<!-- 用来提示用户上传图片 -->
<view class="weui-uploader__input-box pic" bindtap="chooseImg"> </view>
</view>
</view>
js:
// 上传图片
chooseImg: function (e) {
var that = this;
var imgs = this.data.imgs;
if (imgs.length >= 3) {
that.setData({
lenMore: 1
});
setTimeout(function () {
that.setData({
lenMore: 0
});
}, 2500);
return false;
}
wx.chooseImage({
count: 3,
sizeType: ['original', 'compressed'], // 原图,压缩图
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
var imgs = that.data.imgs;
var fileIds = that.data.fileIds;
// console.log(tempFilePaths + '----');
for (var i = 0; i < tempFilePaths.length; i++) {
if (imgs.length >= 3) {
that.setData({
imgs: imgs
});
return false;
} else {
imgs.push(tempFilePaths[i]);
}
wx.uploadFile({
url:ajax.host + 'api/repair/upload',
filePath: tempFilePaths[i],
header: {
"Content-Type": "multipart/form-data"
},
formData: {id:""},
name: 'file',
success(res) {
var data = JSON.parse(res.data);
imgs.push(data.data)
fileIds.push(data.data.id)
that.setData({
imgs:imgs,
fileIds:fileIds
})
},
fail:function(res){
console.log(res)
}
})
}
that.setData({
imgs:imgs
})
}
});
},
// 删除图片
deleteImg: function (e) {
var _this = this;
var imgs = _this.data.imgs;
var index = e.currentTarget.dataset.index;
var id= this.data.id;
var fileIds =_this.data.fileIds;
imgs.splice(index, 1);
fileIds.splice(index,1);
_this.setData({
imgs: imgs,
fileIds:fileIds
});
},
wxss:
.pic {
position:relative;
margin-bottom:9px;
}
.delete-btn{
position: absolute;
top: 0;
right: 0;
}