微信小程序 一键下载多张图片和预览单张下载
js文件代码
Page({
data: {
imglist: [
'https://timgs.top1buyer.com/admin/special/special_img_20190301160008479.jpg',
'https://timgs.top1buyer.com/admin/special/special_img_20190301160013201.jpg',
'https://timgs.top1buyer.com/admin/special/special_img_20190301160015969.jpg',
'https://timgs.top1buyer.com/admin/special/special_img_20190301160025498.jpg',
'https://timgs.top1buyer.com/admin/special/special_img_20190301160031519.jpg',
'https://timgs.top1buyer.com/admin/special/special_img_20190301160042689.jpg',
'https://timgs.top1buyer.com/admin/special/special_img_20190301160108243.jpg',
'https://timgs.top1buyer.com/admin/special/special_img_20190301160111756.jpg'
],
imgNew: []
},
// 点击一键下载图片按钮
DownloadImgList() {
var that = this;
if (that.data.imglist.length == 0) { // 判断数组是否有图片
wx.showToast({
title: '暂无图片下载',
icon: 'none',
duration: 2000
});
return false;
}
// 判断用户是否授权
wx.getSetting({
success: function (res) {
if (res.authSetting["scope.writePhotosAlbum"] == false) {
wx.showToast({
title: '您还未授权保存相册,请授权',
icon: 'none',
duration: 2000
})
wx.openSetting({
success: function (res) {
if (res.authSetting["scope.writePhotosAlbum"] == true) {
// 保存相册
that.dowImg();
}
if (res.authSetting["scope.writePhotosAlbum"] == false) {
wx.showToast({
title: '授权失dsds败!',
icon: 'none',
duration: 2000
})
}
}
});
} else {
// 遍历所有图片
for (let i = 0; i < that.data.imglist.length; i++) {
wx.downloadFile({
url: that.data.imglist[i], // 需下载的每一张图片路径
success: function (res) {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function (response) {
if (response.errMsg == "saveImageToPhotosAlbum:ok") {
wx.showToast({
title: '下载成功',
icon: 'success',
duration: 2000
})
}
}
});
},
fail: function () {
wx.showToast({
title: '下载失败',
icon: 'none',
duration: 2000
})
}
});
}
}
}
});
},
// 图片预览和单独下载
aloneDow(e) {
let src = e.currentTarget.dataset.src; //获取data-src
let imgList = e.currentTarget.dataset.list; //获取data-list
let that = this;
imgList.forEach(function (item, index) {
console.log(item); //这里的item就是从数组里拿出来的每一个每一组
that.setData({
imgNew: that.data.imgNew.concat(item) // 添加到新数组
});
});
wx.previewImage({
current: src, // 当前显示图片的http链接
urls: this.data.imgNew // 需要预览的图片http链接列表
});
}
});
wxml文件:
<view bindtap="DownloadImgList">下载</view>
wxss文件:
.dowimg{
margin: 0 0 50rpx 30rpx;
width: 200rpx;
height: 80rpx;
line-height: 80rpx;
text-align: center;
color: #FFFFFF;
background-color: #07c160;
font-weight: 500;
border-radius: 10rpx;
}
.imglist{
display: flex;
flex-wrap: wrap;
}
.imgitem{
margin: 0 10rpx 10rpx;
width: 230rpx;
height: 230rpx;
}
image{
display: block;
width: 100%;
height: 100%;
}