概述
此功能较基础,跟着官方开发文档步骤即可实现
分析
上传功能借助开发文档中 api
- chooseImage
实现
预览功能是借助api
- perviewImage
实现
删除图片则是通过操控数组实现
代码示例
<view class="imgBox">
<!--图片展示盒子 -->
<view class="showImgBox">
<block wx:for="{{showImgList}}" wx:key="index">
<image src="{{item.showImg}}" catchtap="perviewImgHandle" data-url="{{item.showImg}}"></image>
<image src="/image/common/icon_close.png" catchtap="delImgHandle" data-index={{index}}></image>
</block>
</view>
<!--上传提示盒子 限制只能上传3张图片-->
<view wx:if="{{shouList.length < 3}}" catchtap="addImgHandle" class="addImgBox">
<text>请上传图片</text>
</view>
</view>
const app = getApp()
// 引入封装方法 util
const util = require('../../util/util.js')
page({
data:{
showImgList:[],
uploadImgList:[],
},
// 上传图片
addImgHandle:function(){
var that = this;
wx.chooseImage({
count:1, //最多可以选择的图片张数
sizeType['original', 'compressed'], //所选的图片的尺寸
sourceType:['album', 'camera'], //选择图片的来源
success(res){
// tempFilePath可以作为 img 标签的 src 属性显示图片
const tempFilePaths = res.tempFilePaths;
wx.uploadFile({
url:app.globalData.apiSever + '/Rent/UploadRentImg',
filePath:tempFilePaths[0], //要上传文件资源的路径 (本地路径)
name:'file',
formData:{},
success(result){
console.log(result);
// 通过打印出控制台是一段字符串(如图1可见),转化成Json 对象更符合平时接口返回的数据
var data = JSON.parse(result.data);
// 如果请求成功的话 Code 应为100
if(data.Code == '100'){
var showImgList = that.data.showImgList;
var uploadImgList = that.data.uploadImgList;
// 将服务器返回的长短地址分别push 到数组中
showImgList:.push(data.Data.FullImgUrl);
uploadImgList.push(data.Data.ImgUrl);
that.setData({
showImgList:showImgList,
uploadImgList:uploadImgList
},function(){
wx.showToast({
title: '上传成功',
icon: "success",
mask: true,
})
})
}
}
})
}
})
},
//预览图片
perviewImgHandle:function(e){
var that = this;
var list = that.data.showImgList;
var url = e.currentTarget.dataset.url;
wx.perviewImage({
urls:list,
current:url,
})
}
//删除图片
delImgHandle:function(e){
var that = this;
var list = that.data.showImgList;
var upList = that.data.uploadImgList;
var index = e.currentTarget.dataset.index;
wx.showModal({
content:'您确定要删除此张图片吗',
showCancel:true,
title:'提示',
success(res){
if(res.confirm){
// splice()方法可从数组的指定位置删除指定数量元素
list.splice(index,1),
upList.splice(index,1)
that.setData({
showImgList:list,
uploadImgList:upList
})
}
}
})
}
})
(图1)