添加图片
chooseImg: function (e) {
var that = this;
var imgs = this.data.imgs;
if (imgs.length >= 9) {
this.setData({
lenMore: 1
});
wx.showToast({
duration: 1000,
icon: 'none',
title: '图片上传张数过多',
})
setTimeout(function () {
that.setData({
lenMore: 0
});
}, 2500);
return false;
}else{
wx.chooseImage({
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths;
var imgs = that.data.imgs;
console.log(imgs)
for (var i = 0; i < tempFilePaths.length; i++) {
if (imgs.length >= 9) {
that.setData({
imgs: imgs
});
return false;
} else {
imgs.push(tempFilePaths[i]);
}
}
that.setData({
imgs: imgs
});
}
});
}
},
删除图片
deleteImg: function (e) {
var imgs = this.data.imgs;
var index = e.currentTarget.dataset.index;
imgs.splice(index, 1);
this.setData({
imgs: imgs
});
},
预览图片
previewImg: function (e) {
var index = e.currentTarget.dataset.index;
var imgs = this.data.imgs;
wx.previewImage({
current: imgs[index],
urls: imgs
})
},
上传图片
fb: function (e) {
wx.showLoading({
title: '上传中',
})
let promiseArr = [];
for (let i = 0; i < this.data.imgs.length; i++) {
promiseArr.push(new Promise((reslove, reject) => {
let item = this.data.imgs.length;
wx.uploadFile({
url: '你的后台?imgcount=' + item,
filePath: this.data.imgs[i],
name: 'file',
formData: {
'wtid': this.data.imgs
},
success: res => {
reslove();
wx.hideLoading();
wx.showToast({
title: "上传成功",
})
},
fail: function (res) {
wx.hideLoading();
wx.showToast({
title: "上传失败",
})
}
})
}));
}
Promise.all(promiseArr).then(res => {
console.log("图片上传完成后再执行");
wx.request({
url: '',
data: {
imgcount: this.data.imgs.length,
},
success: (res) => {
this.setData({
imgs: [],
}), setTimeout(function() {
wx.navigateBack({
delta: 1
});
}, 1000)
}
})
})
},
wxml
<view class="form-content">
<view class="pages">
<view class='images-box'>
<view class="img-box" wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
<image class="img" src="{{item}}" data-index="{{index}}" mode="aspectFill" bindtap="previewImg"></image>
<view class='img-delect' data-index='{{index}}' catchtap="deleteImg">
<image class='img' src='https://img-blog.csdnimg.cn/20191209212952351.png'></image>
</view>
</view>
<view class='img-box' bindtap='chooseImg' wx:if="{{imgs.length<9}}">
<image class='img' src='https://img-blog.csdnimg.cn/20190922105114571.png'></image>
</view>
</view>
</view>
</view>
wxss
.pages{
width: 98%;
margin: auto;
overflow: hidden;
background-color: rgba(221, 221, 221, 0.527);
}
.images_box{
width: 100%;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
}
.img-box{
border: 5rpx;
border-style: solid;
border-color: rgba(0, 0, 0, 0.452);
width: 200rpx;
height: 200rpx;
margin-left: 35rpx;
margin-top: 20rpx;
margin-bottom: 20rpx;
position: relative;
float: left;
}
.img-delect{
width:50rpx;
height:50rpx;
border-radius:50%;
position:absolute;
right:-20rpx;
top:-20rpx;
}
.img{
width: 100%;
height: 100%;
}