小程序多张图片的上传,查看与删除
效果:
页面JS代码
//选择图片
chooseImage(e) {
if (this.data.viconPlay == false) {
this.setData({
imageShow: '/images/yunyinShow.png',
viconPlay: true
});
}
const count = 6 - this.data.imageFiles.length
Common.uploadImage(count, 1).then(res => {
this.setData({
imageFiles: res
})
}).catch(err => {
console.error(err);
})
},
//添加图片
addImage(e) {
if (this.data.viconPlay == false) {
this.setData({
imageShow: '/images/yunyinShow.png',
viconPlay: true
});
}
const count = 6 - this.data.imageFiles.length
Common.uploadImage(count, 1).then(res => {
this.setData({
imageFiles: this.data.imageFiles.concat(res)
})
}).catch(err => {
console.error(err);
})
},
//删除图片的方法
remove: function(array, val) {
for (var i = 0; i < array.length; i++) {
if (array[i] == val) {
array.splice(i, 1);
}
}
return -1;
},
//删除图片
deleteImage(e) {
const imageFiles = this.data.imageFiles;
const index = e.currentTarget.dataset.id
this.remove(imageFiles, index)
this.setData({
imageFiles
});
},
//放大图片
previewImage(e) {
if (this.data.viconPlay == false) {
this.setData({
imageShow: '/images/yunyinShow.png',
viconPlay: true
});
}
wx.previewImage({
current: e.currentTarget.dataset.id, // 当前显示图片的http链接
urls: this.data.imageFiles // 需要预览的图片http链接列表
});
},
调用的方法
uploadImage(count = 1, uploadType) {
return new Promise((resolve, resject) => {
wx.chooseImage({
count,
sizeType: ["compressed"], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ["album", "camera"], // 可以指定来源是相册还是相机,默认二者都有
success: (res) => {
const tempFilePaths = res.tempFilePaths;
const list = [];
for (let i = 0; i < tempFilePaths.length; i++) {
wx.uploadFile({
url: `${app.globalData.apiHost}/qiniu/upload-image${app.globalData.t}`,
filePath: tempFilePaths[i],
name: 'file',
async: false,
header: {
'X-Auth-Token': app.getToken()
},
success: res => {
if (res.statusCode == 200) {
wx.showLoading({
title: '图片上传中...',
mask: true
})
const imgSrc = JSON.parse(res.data).d.filepath;
list.push(imgSrc);
console.log(list)
if (uploadType != 1) {
resolve(list);
// wx.hideLoading();
} else if (uploadType == 1) {
setTimeout(function () {
resolve(list);
wx.hideLoading();
}, 1200 * tempFilePaths.length)
}
} else {
resject(res);
}
},
fail: (err => {
resject(err);
})
})
}
},
fail: err => {
resject(err);
}
})
})
}
此方法还待优化,因为执行顺序原因在方法里添加了定时器来控制图片加载,但是这样有一些不确定因素