效果:
一,下面是上传图片的效果
image.js代码:
Page({
//选择相册或拍照
data: {
imgs: []
},
//上传图片
chooseImg: function (e) {
var that = this;
var imgs = this.data.imgs;
if (imgs.length >= 9) {
this.setData({
lenMore: 1
});
setTimeout(function () {
that.setData({
lenMore: 0
});
}, 2500);
return false;
}
wx.chooseImage({
// count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
var imgs = that.data.imgs;
// console.log(tempFilePaths + '----');
for (var i = 0; i < tempFilePaths.length; i++) {
if (imgs.length >= 9) {
that.setData({
imgs: imgs
});
return false;
} else {
imgs.push(tempFilePaths[i]);
}
}
// console.log(imgs);
that.setData({
imgs: imgs
});
}
});
},
// 删除图片
deleteImg: function (e) {
var that = this;
var imgs = that.data.imgs;
var index = e.currentTarget.dataset.index;//获取当前长按图片下标
wx.showModal({
title: '提示',
content: '确定要删除此图片吗?',
success: function (res) {
if (res.confirm) {
console.log('点击确定了');
imgs.splice(index, 1);
} else if (res.cancel) {
console.log('点击取消了');
return false;
}
that.setData({
imgs: imgs
});
}
})
},
// 预览图片
previewImg: function (e) {
//获取当前图片的下标
var index = e.currentTarget.dataset.index;
//所有图片
var imgs = this.data.imgs;
wx.previewImage({
//当前显示图片
current: imgs[index],
//所有图片
urls: imgs
})
}
})
image.wxml代码:
<button class="upload-img-btn" bindtap="chooseImg">上传</button>
<view class="img" wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
<image src="{{item}}" data-index="{{index}}" mode="widthFix" bindtap="previewImg" bindlongpress="deleteImg"></image>
</view>
如果需要上传图片保存到服务器上,请参考地址:https://blog.csdn.net/m0_37865510/article/details/81223757
有问题,随时联系,邮箱地址:[email protected],留言也行的哦