微信小程序本地上传图片,在小程序开发文档上面有说明:
wx.chooseImage(Object object) | 微信开放文档
wx.previewImage(Object object) | 微信开放文档
wxml: 图片用wx:for循环,后面用带有加号的图片。
<view class="content">
<text>微信小程序练习demo</text>
<view class="upload">
<view class="imgArr" wx:if="{{upImage.length > 0}}" wx:for="{{upImage}}" wx:key="index">
<image src="{{item}}" class="upImage" mode="widthFix" bindtap="previewImage" data-src="{{item}}"></image>
<image class="delete" bindtap="delete" src="../../images/cha.png" data-id="{{index}}"></image>
</view>
<image wx:if="{{upImage.length < 9}}" src="../../images/shangc.png" class="upImage" bindtap="uploadImg"></image>
</view>
</view>
wxss:
.content{
width: 100%;
padding: 0 20rpx;
}
.upload{
margin-top: 20rpx;
width: 100%;
height: 200rpx;
display: flex;
flex-wrap: wrap;
}
.imgArr{
display: flex;
position: relative;
}
.imgArr:nth-child(3n+2){
margin-bottom: 15rpx;
}
.imgArr .upImage{
margin-right:15rpx;
}
.upImage{
width: 200rpx;
height: 200rpx;
}
/* .upImage:nth-child(2){
margin-left: 15rpx;
} */
.delete{
width: 40rpx;
height: 40rpx;
position: absolute;
top: -5rpx;
right: -5rpx;
}
js:
data: {
upImage:[]
},
//图片上传
uploadImg(){
let that = this;
wx.chooseImage({
count: 9,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res){
console.log(res);
const tempFilePaths = res.tempFilePaths[0];
let old_data = that.data.upImage;
let new_data = res.tempFilePaths;
if(that.data.upImage.length + res.tempFilePaths.length <=9){
that.setData({
upImage : old_data.concat(new_data)
})
console.log(that.data.upImage)
}else{
wx.showToast({
title: '上传图片不能超过9张',
icon:"none"
})
}
}
})
},
//图片预览
previewImage(e){
let that = this;
let current = e.currentTarget.dataset.src;
console.log(current);
let urls = that.data.upImage;
console.log(urls);
// urls.push(current);
wx.previewImage({
current: current, // 当前显示图片的http链接
urls: urls // 需要预览的图片http链接列表
})
},
//图片删除
delete(e){
console.log(e);
let that = this;
let upImage = that.data.upImage;
let index = e.currentTarget.dataset.id;
console.log(index);
wx.showModal({
title:"提示",
content:"确定要删除此图片吗?",
success:function (res) {
if(res.confirm){
console.log("点击了确定");
upImage.splice(index,1);
that.setData({
upImage
})
}else if(res.cancel){
console.log("点击了取消");
}
}
})
},
最后的效果大概是: