微信小程序wxml标签样式如下:
<view class="task_img">
<block wx-if="{{workImg}}">
<view class="item" wx:for="{{workImg}}" wx:key="{{index}}">
<image src="{{item}}" bindtap="onImages" data-index="{{index}}"></image>
<view class='delete' bindtap='deleteImg' data-index="{{index}}">
<text>删除</text>
</view>
</view>
</block>
<view class="img-wrap" bindtap="uploadPhotos">
<image class="task_icon" src="../../image/upload.png">
</image>
<view class="task_uploader">
<text>上传照片</text>
<text>(最多9张)</text>
</view>
</view>
</view>
微信小程序wxss样式如下:
.task_img {
background: #FFFFFF;
padding: 20rpx 30rpx;
display: flex;
flex-wrap: wrap;
}
.item {
width: 147rpx;
height: 147rpx;
position: relative;
border-radius: 10rpx;
margin-left: 40rpx;
margin-bottom: 20rpx;
}
.item image {
width: 100%;
height: 100%;
border-radius: 10rpx;
}
.delete {
position: absolute;
width: 147rpx;
height: 32rpx;
background: #363636;
border-radius: 0px 0px 10rpx 10rpx;
opacity: 0.67;
text-align: center;
bottom: 0rpx;
line-height: 28rpx;
}
.delete text {
font-size: 20rpx;
color: #FFFFFF;
letter-spacing: 1rpx;
}
微信小程序js效果如下:
import { geHomeworkSubmit } from "../apiFile/exam";
import apiUrl from "../../utils/apiUrl";
Page({
data: {
dialogShow: false,
workImg: [],
content: ''
},
handleCancel() {
this.setData({
dialogShow: false,
})
},
uploadPhotos() {
var that = this
if (that.data.workImg.length >= 9) {
wx.showToast({
title: "最多只能上传9张",
icon: "none",
duration: 1500
})
return
}
wx.chooseImage({
count: 9,
sizeType: ["original", "compressed"],
sourceType: ["album", "camera"],
success: function (res) {
var tempFilePaths = res.tempFilePaths
for (var i = 0; i < tempFilePaths.length; i++) {
wx.uploadFile({
url: apiUrl + '/base/upload/upload_image',
filePath: tempFilePaths[i],
name: "upfile",
header: {
"content-type": "multipart/form-data"
},
success: function (res) {
if (res.statusCode == 200) {
wx.showToast({
title: "上传成功",
icon: "none",
duration: 1500
})
console.log('res', JSON.parse(res.data))
that.data.workImg.push(JSON.parse(res.data).body)
that.setData({
workImg: that.data.workImg
})
}
},
fail: function (err) {
wx.showToast({
title: "上传失败",
icon: "none",
duration: 2000
})
},
complete: function (result) {
console.log(result.errMsg)
}
})
}
}
})
},
deleteImg(e) {
var that = this
wx.showModal({
title: "提示",
content: "是否删除图片",
success: function (res) {
if (res.confirm) {
for (var i = 0; i < that.data.workImg.length; i++) {
if (i == e.currentTarget.dataset.index) that.data.workImg.splice(i, 1)
}
that.setData({
workImg: that.data.workImg
})
} else if (res.cancel) {
console.log("用户点击取消")
}
}
})
},
onImages(e) {
let {workImg} = this.data
let {index} = e.currentTarget.dataset
wx.previewImage({
current: workImg[index],
urls: workImg
})
},
})
效果如下: 