小程序官方有自己的上传图片系列的接口
wx.chooseMedia // 本地选择视频或者图片
wx.uploadFile // 上传视频或者图片
wx.previewImage // 预览上传的视频或图片
本地选择图片并上传,这里我给的最多 6张
新增图片的占位图
<!-- wxml代码片段 -->
<view class="photo">
<image class="upload-photo" wx:if="{{photoList.length < 6}}" src="../images/add.png" mode="" bindtap="choosePhoto"/>
<!-- 注意bindtap 和 catchtap的区别,catchtap可以阻止事件冒泡-->
<view class="photo-list" wx:for="{{photoList}}" data-index="{{index}}" bindtap="previewImg" wx:key="index">
<image src="{{item}}" mode=""/>
<view class="del" catchtap="delImg" data-index="{{index}}">x</view>
</view>
</view>
// 选择本地图片
choosePhoto(e) {
let that = this
if(this.data.photoList.length < 6) {
wx.chooseMedia({
count: 6, // 最多同时选 6张
mediaType: 'image',
success(res) {
let {tempFiles} = res
tempFiles.forEach((item, index) => {
that.uploadImg(item.tempFilePath) // 循环执行上传放法,实现多张图片,同时上传
})
},
fail(err) {
console.log(err)
}
})
} else {
wx.showToast({
title: '最多上传6张图片',
icon: 'none'
})
}
},
向后台发送图片
uploadImg(imgSrcList) {
var that = this;
let {photoList} = this.data;
wx.showLoading({
title: "加载中"
});
wx.uploadFile({
url: "向后端发送的接口",
filePath: imgSrcList, // 本地图片临时路径
name: "file", // 上传图片key
formData: { // 额外发送的参数},
success: function (res) {
wx.hideLoading();
// 成功以后的回调
if (res.statusCode == 200) { // 请求状态拦截
let data = JSON.parse(res.data)
photoList.push(data.data.url) // 后端返回的图片地址
that.setData({ // 添加进data参数中
photoList
})
}
},
fail(err) {
// 失败的回调
}
})
}
预览图片:在新页面中全屏预览图片。预览的过程中用户可以进行保存图片、发送给朋友等操作
previewImg() {
let {index} = e.currentTarget.dataset
let {photoList} = this.data
wx.previewImage({
current: photoList[index | 0], // 当前显示图片的http链接 默认urls[0]
urls: photoList // 需要预览的图片http链接列表
})
},
删除图片:
delImg(e) {
let that = this
let {index} = e.currentTarget.dataset
let {photoList} = this.data
wx.showModal({
title: '提示',
content: '是否删除当前照片',
success (res) {
if (res.confirm) {
photoList.splice(index, 1)
that.setData({
photoList
})
}
}
})
},
WXSS 样式没有贴出来,感觉写的不是很好,你们可以根据自己的需要自行修改图片展示效果,也可以留言找我要 前端路漫漫,一起学习,一起探索,有什么问题,留言看到及时回复