如题
最近遇到了需要保存图片到相册需求,在网上找了半天,很多方法看着流程都没问题,但是借鉴过来都不太行,很多是模拟器上能用,真机上不行。自己也试了很多方法,找到一个适合自己的方法,方法略显粗糙,后期有空再打磨罢。
使用了微信的api有 wx.downloadFile,此api可以将网络地址图片或者本地地址图片转为临时地址,方便后面的下载。wx.saveImageToPhotosAlbum是将上地址的图片保存到本地相册,因为是多个图片下载,这里借鉴了网上的Promise.all()方法。
声明!保存图片涉及到微信向小程序授权的问题,这里暂时不考虑授权问题和点击拒绝授权后再次点击保存按钮从新拉起授权的操作。如需要请自行爬帖。
这是html
<view class="prodBtn" style="margin-top: 30rpx;" bindtap="downloadimg">保存图片</view>
js部分
downloadimg() {
if (this.data.downloadList == null || this.data.downloadList == []) {
wx.showToast({
title: '请选择需要保存的图片 ',
icon: "none",
})
return
} else {
let arr = this.data.downloadList.map(item => {
return this.data.prod.imgs[item]
}) //这里是我处理需要下载的图片链接
this.downloadImgs(arr)
}
},
//此方法是单独下载每个图片,使用promise返回后通过 .then()方法继续下一个
getTempPath(url) {
return new Promise((resolve, reject) => {
wx.downloadFile({
url: url,
success: function (res) {
var temp = res.tempFilePath
wx.saveImageToPhotosAlbum({
filePath: temp,
success(res) {
return resolve(res)
},
fail: function (err) {
reject(url + JSON.stringify(err))
}
})
// wx.saveImageToPhotosAlbum({
// filePath: temp,
// success: function (res) {
// return resolve(res)
// },
// fail: function (err) {
// reject(url + JSON.stringify(err))
// }
// })
},
fail: function (err) {
reject(url + JSON.stringify(err))
}
})
})
},
//此方法循环将网络地址图片下载为临时地址图片,方便保存处理
// 这里使用了promise具体思路请看代码,不再赘述
downloadImgs(urls) {
wx.showLoading({
title: '图片下载中',
mask: true
})
const imageList = []
// 循环数组
for (let i = 0; i < urls.length; i++) {
imageList.push(this.getTempPath(urls[i]))
}
const loadTask = []
let index = 0
while (index < imageList.length) {
loadTask.push(
new Promise((resolve, reject) => {
// 将数据分割成多个promise数组
Promise.all(imageList.slice(index, (index += 8)))
.then(res => {
resolve(res)
})
.catch(err => {
reject(err)
})
})
)
}
// Promise.all 所有图片下载完成后弹出
Promise.all(loadTask)
.then(res => {
wx.showToast({
title: '下载完成',
duration: 3000
})
})
.catch(err => {
wx.showToast({
title: `下载完成`,
icon: 'none',
duration: 3000
})
})
}
实现过程略显粗糙,请见谅哈!