废话不多说,直接撸代码
wxml事件编写
<view class="addPic" >
<view class="addPic_btn" catchtap="chooseImage" wx:if='{
{imagesList.length < 3}}'>
<view style="width: 100%;">
<image src="/image/photo.png" mode="widthFix" lazy-load="true" ></image>
<view>上传图片</view>
</view>
</view>
<block wx:for='{
{imagesList}}' wx:key=''>
<view class="addPic_li">
<image src="{
{item}}" mode="aspectFill" lazy-load="true" data-index='{
{index}}' catchtap="handleImagePreview"></image>
<view class="addPic_close" catchtap="deleteImage" data-index='{
{index}}'>×</view>
</view>
</block>
</view>
js:
// 上传数组(每次上传单张)
chooseImage: function () {
var that = this
let images = that.data.images
wx.chooseImage({
count: 1, //最多可以选择图片的张数
sizeType: ['original', 'compressed'], //所选图片的尺寸,系统自带,原图或压缩图
sourceType: ['album', 'camera'], //选择图片的来源,相册或相机
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths
images = that.data.images.concat(res.tempFilePaths) //concat 返回一个数组,该数组是通过把原数组内的所有参数添加到新数组中生成的。如果要进行的concat()操作的参数是数组,那么添加的是数组的元素,而不是数组。
that.setData({
images: images
})
}
})
},
//上传图片(同时上传多张)
chooseimage: function (e) {
let upload_arr = ['album', 'camera']
var _this = this;
if (_this.data.upload_images.length >= 9) return
wx.chooseImage({
count: 9, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: upload_arr, // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
let tempFilePaths = res.tempFilePaths
wx.showLoading({
title: '上传中',
})
for (let i in tempFilePaths) {
App.request.upload(App.api.uploadFile, tempFilePaths[i], 'file', {}, (res2) => {
console.log(res2);
_this.data.sel_images.push(tempFilePaths[i])
_this.data.upload_images.push(res2.Url)
_this.setData({
upload_images: _this.data.upload_images,
sel_images: _this.data.sel_images,
cover_images: _this.data.upload_images[i],
})
wx.hideLoading()
})
}
}
})
},
// 删除图片
deleteImage: function (e) {
var that = this
let index = e.detail.index
let images = that.data.images
images.splice(index, 1)
that.setData({
images: images
})
console.log(e)
},
// 点击预览效果
handleImagePreview: function (e) {
var that = this
const index = e.detail.index
const images = that.data.images
wx.previewImage({
current: images[index], //当前预览的图片
urls: images, //所有要预览的图片
})
}