小型マイクロチャネルプログラム選択画面、プレビュー画像は、Enterキーを押して画像を削除し、写真をアップロードします。
wxml一部:
<view class='imgs'>
<block wx:for="{{tempFilePaths}}" wx:for-item="image">
<image src="{{image}}" class='addImg' bindtap='previewImage' id="{{image}}" bindlongpress='deleteImage' data-index='{{index}}'></image>
</block>
<image src='../images/add_img.jpg' class='addImg' bindtap='chooseImage' hidden='{{addState}}'></image>
</view>
<view class='btn' bindtap='upload'>上传</view>
JS一部:
Page({
data: {
tempFilePaths: [],//图片路径
addState: false,//添加图片按钮的状态
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
chooseImage: function () {//选择图片
var that = this;
wx.chooseImage({
count: 9,//最多添加9张
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths;
var State = false;
if (res.tempFilePaths.length = 9) {//当选择图片等于9张时,则隐藏添加图片按钮
State = true;
} else {//当选择图片小于9张时,则显示添加图片按钮
State = false;
}
that.setData({
tempFilePaths: res.tempFilePaths,
addState: State
})
}
});
},
previewImage: function (e) {//预览图片
var that = this;
wx.previewImage({
current: e.currentTarget.id, // 当前显示图片的http链接
urls: that.data.tempFilePaths // 需要预览的图片http链接列表
})
},
deleteImage: function (e) {//删除图片
var that = this;
var images = that.data.tempFilePaths;
var index = e.currentTarget.dataset.index;//获取当前长按图片下标
wx.showModal({
title: '提示',
content: '确定要删除此图片吗?',
success: function (res) {
if (res.confirm) {
console.log('点击确定了');
images.splice(index, 1);//通过splice方法删除splice(index,1),删除一个当前元素
var State = false;//删除图片,图片数量肯定小于9,So改变添加图片按钮的状态,使之显示
that.setData({
tempFilePaths: images,
addState: State
});
} else if (res.cancel) {
console.log('点击取消了');
return false;
}
}
})
},
upload: function () {//上传图片到服务器
var that = this;
console.log("img", that.data.tempFilePaths);
wx.uploadFile({
url: 'xxx',//服务器地址
filePath: that.data.tempFilePaths,//图片路径
name: 'file',
formData: {
'imgs': 'imgs'
},
success(res) {
const data = res.data
}
});
}
})