效果图

功能: 上传,删除,预览,九宫格,多张上传,单张上传
wxml
<view class="img_box">
<view class="img_item" wx:for="{{imgList}}" wx:for-item="item">
<image bindtap="preview" data-src="{{item}}" class="img_item_i" src="{{item}}" mode="aspectFill"></image>
<image bindtap="delImg" data-index="{{index}}" src="删除按钮图标地址" class="closeImv"></image>
</view>
<view class="img_item" style=" display: flex;justify-content: center;align-items: center;">
<image wx:if="{{imgList.length<9}}" class="add_icon" style="width:30%;height:30%;display:flex;justify-content:center;align-item:center" bindtap="upload" mode="aspectFill" src="点击上传的图标地址"></image>
</view>
</view>
JS
Page({
data: {
imgList:[]
},
upload(e){ //上传图片
let that=this;
let imgList = that.data.imgList;
let count = 9-imgList.length;
wx.chooseImage({
count: count, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
wx.showLoading({
title: '图片上传中',
})
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths
console.log(tempFilePaths)
let newDatas = {};
for (let keyName in datas) {
newDatas[keyName] = datas[keyName];
}
// 此处循环一个一个上传
for (let i = 0; i < tempFilePaths.length; i++) {
wx.uploadFile({
url: XXX, //仅为示例,非真实的接口地址
filePath: tempFilePaths[i],
name: '文件名字',
formData: newDatas,
success: function (res) {
console.log("res",res)
let datas = JSON.parse(JSON.parse(res.data).data);
console.log(datas)
// 图片展示所用
let imgList = that.data.imgList;
if (datas.code==200){
imgList.push(datas.response.file_path)
that.setData({
imgList
})
wx.hideLoading();
}else{
wx.hideLoading();
wx.showModal({
title: '提示',
content: ‘失败’,
showCancel: false
})
}
//do something
}
})
}
},
fail:function(err){
console.log(err);
}
})
},
preview(e){ //预览图片
let img = e.currentTarget.dataset.src;
let imgList = this.data.imgList;
imgList.push(img);
wx.previewImage({
current: img, // 当前显示图片的http链接
urls: imgList// 需要预览的图片http链接列表
})
},
delImg(e){ //删除图片
let that = this;
console.log('点击删除图片===>',e);
let index = e.currentTarget.dataset.index;
let imgList = that.data.imgList;
wx.showModal({
title: '提示',
content: '删除该图片?',
confirmColor:'red',
success (res) {
if (res.confirm) {
console.log('用户点击确定')
imgList.splice(index,1);
that.setData({
imgList
})
} else if (res.cancel) {
console.log('用户点击取消')
}
}
})
}
)}
wxss
.img_box{
display: flex;
flex-wrap: wrap;
margin: 20rpx;
width: 100%;
}
.img_item_i{
display: block;
width: 100%;
height: 100%;
}
.add_icon{
display: block;
width: 50%;
height: 50%;
}
.img_item {
width: 30%;
height: 210rpx;
position: relative;
margin-right: 2%;
margin-bottom: 2%;
border: 1px solid #c0ccda;
}
.closeImv {
position: absolute;
right: 0rpx;
top: 0rpx;
width: 50rpx;
height: 50rpx;
}