1、最近在做小程序图片上传、预览以及删除功能,下面贴出代码,以供参考和交流。
2、 功能实现图:
3、wxml代码
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">上传照片</view>
</view>
</view>
<view class="upload-imgs" wx:if="{{uploadImages.length > 0}}">
<block wx:for="{{uploadImages}}" wx:for-item="img" wx:key="{{id}}">
<image class="{{index == 1 || index == 4 || index == 7 ? 'mar' : ''}}" src="{{img.imgUrl}}" data-index="{{index}}" bindtap="previewImg" >
<icon type='cancel' class="delete-btn" data-index="{{index}}" catchtap="deleteImg"></icon>
</image>
</block>
</view>
<view class="weui-cell__bd">
<view class="images">
<image class="upload-img" src="/pages/images/equrepair/button.jpg" bindtap="chooseImage"></image>
</view>
</view>
</view>
3、wxcss局部代码
.page .upload-imgs {
padding-left: 3%;
margin-bottom: 2%;
position:relative;
}
.upload-imgs image {
width: 30%;
height: 107px;
padding: 1%;
position:relative;
}
.delete-btn{
position: absolute;
top: 0;
right: 0
}
4、js代码
/**
*预览图片
**/
previewImg: function (e) {
var that = this;
//获取当前图片的下标
var index = e.currentTarget.dataset.index;
//所有图片
var imgArr = [];
var objkeys = Object.keys(that.data.uploadImages); //{imgUrl: "https://20201020/1603.png"}
for(var i=0; i< objkeys.length;i++){
imgArr.push(that.data.uploadImages[i]["imgUrl"]); //将img图片链接重新添加到imgarr数组,不然会报错,urls需要数组类型的数据,object会报错
}
wx.previewImage({
//当前显示图片
current: imgArr[index],
//所有图片
urls: imgArr
})
},
/**
*删除图片
**/
deleteImg: function (e) {
var that = this;
var imgs = that.data.uploadImages;
var index = e.currentTarget.dataset.index;
imgs.splice(index, 1);
this.setData({
uploadImages: imgs
});
},