问题
小程序保存图片到相册一直无响应,保存不成功
分析
小程序保存图片到相册主要用到以下三点:
wx.downloadFile下载图片
wx.openSetting授权
wx.saveImageToPhotosAlbum图片保存到本地
查看wx.downloadFile请求正常响应,不过wx.saveImageToPhotosAlbum有报错信息,下面列出真机跟调试都出现的报错信息
err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response"
出现这报错信息,一般保存图片用户没有授权,可将授权方法wx.openSetting放入wx.showModal提示框中
wx.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success: res=> {
wx.openSetting({
success(res) {
console.log("success", res)
},
fail(err) {
console.log("fail", err)
},
complete(res) {
console.log("finish", res)
}
})
}
})
保存图片完整代码示例
wx.downloadFile({
url: e.currentTarget.dataset.contractimg,
success (res) {
if (res.statusCode === 200) {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
util.hideToast();
wx.showModal({
title: '图片保存成功',
content: '图片成功保存到相册了',
showCancel: false,
confirmText: '好哒',
confirmColor: '#5096cd',
success: function (res) {
if (res.confirm) {
console.log('用户点击确定');
}
}
})
},
fail (err) {
util.hideToast()
if (
err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" ||
err.errMsg === "saveImageToPhotosAlbum:fail auth deny" ||
err.errMsg === "saveImageToPhotosAlbum:fail authorize no response"
) {
wx.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success: res=> {
wx.openSetting({
success(res) {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
wx.showModal({
title: '提示',
content: '获取权限成功,再次点击下载即可保存',
showCancel: false,
})
} else {
wx.showModal({
title: '提示',
content: '获取权限失败,将无法保存到相册哦~',
showCancel: false,
})
}
},
fail(err) {
console.log("fail", err)
},
complete(res) {
console.log("finish", res)
}
})
}
})
} else if (err.errMsg === "saveImageToPhotosAlbum:fail cancel") {
wx.showModal({
title: '提示',
content: '取消了保存图片,再次点击下载即可保存',
showCancel: false,
})
} else {
wx.showModal({
title: '提示',
content: err.errMsg,
showCancel: false,
})
}
}
})
} else {
util.hideToast()
wx.showModal({
title: '提示',
content: "图片下载失败",
showCancel: false,
})
}
},
fail () {
util.hideToast()
wx.showModal({
title: '提示',
content: "图片下载失败",
showCancel: false,
})
}
})