小程序上传图片
wxml
<!-- 容器 -->
<view class='ui_uploader_cell'>
<!-- 根据已选择的图片临时路径数组展示图片-->
<view class='ui_uploader_item' wx:for="{{uploaderList}}" wx:key="index">
<!-- 删除-->
<icon class='ui_uploader_item_icon' bindtap='clearImg' data-index="{{index}}" type="clear" size="20" color="red"/>
<!-- 图片-->
<image bindtap='showImg' data-index="{{index}}" src='{{item}}'></image>
</view>
<!-- 上传按钮+框 -->
<view class='ui_uploader' bindtap='upload' wx:if="{{showUpload}}">+++++++</view>
</view>
js
// pages/updown/updown.js
Page({
/**
* 页面的初始数据
*/
data: {
uploaderList: [],
},
// 删除图片
clearImg:function(e){
var nowList = [];//新数据
var uploaderList = this.data.uploaderList;//原数据
for (let i = 0; i < uploaderList.length;i++){
if (i == e.currentTarget.dataset.index){
continue;
}else{
nowList.push(uploaderList[i])
}
}
this.setData({
uploaderNum: this.data.uploaderNum - 1,
uploaderList: nowList,
showUpload: true
})
},
//展示图片
showImg:function(e){
var that=this;
wx.previewImage({
urls: that.data.uploaderList,
current: that.data.uploaderList[e.currentTarget.dataset.index]
})
},
//上传图片
upload: function(e) {
var that = this;
wx.chooseImage({
count: 9 - that.data.uploaderNum, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
console.log(res)
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
let tempFilePaths = res.tempFilePaths;
let uploaderList = that.data.uploaderList.concat(tempFilePaths);
if (uploaderList.length==9){
that.setData({
showUpload:false
})
}
that.setData({
uploaderList: uploaderList,
uploaderNum: uploaderList.length,
})
}
})
},
})