微信小程序批量上传图片到服务器,并实现预览,删除功能

js代码
Page({
/**

页面的初始数据
/
data:
{
files: [], //门店图片信息,数组图片保存作为数据源
},
/
*

多图片上传
*/
chooseImage: function (e) {
var that = this;
if (that.data.files.length > 1) {
resource.notishi(“抱歉最多只允许上传三张图片哟~”);
return false;
}
wx.chooseImage({
count: 1, //默认9张,这里设置三张
sizeType: [‘original’, ‘compressed’], // 可以指定是原图还是压缩图,默认二者都有
sourceType: [‘album’, ‘camera’], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
that.setData({
files: res.tempFilePaths
})
}
})
1
2
3
4
5
6
7
8
9
10
11
},
uploadfile:function(){
var that = this
//多图片上传,tempFilePaths本地图片地址为一个数组,遍历调用服务器图片上传接口即可实现多图保存
for (var i = 0; i < that.data.files.length; i++) {
console.log(‘图片地址名称’ + that.data.files[i]);
wx.uploadFile({
url: ‘http://192.168.1.57:45088/api/uploadfile’, //此处为实际接口地址
filePath: that.data.files[i], //获取图片路径
header: {
‘content-type’: ‘multipart/form-data’
},
name: ‘upload’,
success: function (res) {
wx.hideLoading();
let Result = JSON.parse(res.data);
console.log(Result);//接收返回来的服务器图片地址
},
fail: function (res) {
wx.hideLoading()
wx.showToast({
title: ‘上传失败,请重新上传’,
icon: ‘none’,
duration: 2000
})
},
})
}
},
//图片预览
previewImage: function (e) {
wx.previewImage({
current: e.currentTarget.id, // 当前显示图片的http链接
urls: this.data.files // 需要预览的图片http链接列表
})
},

// 删除图片
deleteImg: function (e) {
var that = this;
var imgs = that.data.files;
var index = e.currentTarget.dataset.index;//获取当前长按图片下标
wx.showModal({
title: ‘提示’,
content: ‘确定要删除此图片吗?’,
success: function (res) {
if (res.confirm) {
console.log(‘点击确定了’);
imgs.splice(index, 1);
} else if (res.cancel) {
console.log(‘点击取消了’);
return false;
}
that.setData({
files: imgs
});
}
})
},
})

wxml代码:

门店照片(请选择三张)

猜你喜欢

转载自blog.csdn.net/weixin_43776965/article/details/89705407