不要使用默认的保存路径
wx.downloadFile 和 wx.saveImageToPhotosAlbum 的 filePath 使用自定义的
saveToPhone() {
const url = wx.env.USER_DATA_PATH + "/" + new Date().getTime().toString() + this.data.url.slice(this.data.url.lastIndexOf('.'))
console.log(url)
wx.showLoading({
title: '保存中...'
})
wx.downloadFile({ //下载文件资源到本地
url: this.data.url, // 网络图片的地址
filePath: url,
success: function (res) {
console.log(res);
//图片保存到本地
if (res.statusCode === 200) {
wx.saveImageToPhotosAlbum({
filePath: url,
success: function (data) {
wx.hideLoading()
wx.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
})
let fileMgr = wx.getFileSystemManager()
fileMgr.unlink({
filePath: url,
success: () => {
console.log('删除缓存成功!')
}
})
},
fail: function (err) {
if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
console.log("当初用户拒绝,再次发起授权")
wx.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success: () => {
wx.openSetting({
success(settingdata) {
console.log("settingdata", settingdata)
if (settingdata.authSetting['scope.writePhotosAlbum']) {
wx.showModal({
title: '提示',
content: '获取权限成功,再次点击图片即可保存',
showCancel: false,
})
} else {
wx.showModal({
title: '提示',
content: '获取权限失败,将无法保存到相册哦~',
showCancel: false,
})
}
},
fail(failData) {
console.log("failData", failData)
},
complete(finishData) {
console.log("finishData", finishData)
}
})
}
})
}
},
complete(res) {
console.log(res);
wx.hideLoading()
}
})
}
}
})
},