最近项目中遇到一个需求,就是要保存商品的图片到手机相册,一开始我还以为挺简单的,毕竟文档在哪里,小程序一般都是拿来就用的,可是这个就是不行,遇到提示saveImageToPhotosAlbum:fail file not found问题,最后发现是用户没有授权。解决这个问题又发现小程序又无法保存图片,这明明是同意了为什么还不行,经过研究发现,我没要先获取图片信息在进行保存就可以了。我使用的是uni-app来开发的,如果你用原生小程序开发的话就把uni改成wx吧!在这里我强烈推荐大家使用uni-app来开发小程序。具体什么好处,大伙可以去看看uni-app的文档,好了不多说看代码。
/* 如果是这么写的,可以不使用button设置open-type属性*/
/* 判断是否授权 */
uni.authorize({
/* 这个就是保存相册的 */
scope: 'scope.writePhotosAlbum',
success() {
/* 保存图片方法 */
img();
},
complete(res) {
console.log(res);
/* 这里判断一下如果没有授权重新打开设置选项 */
uni.getSetting({
success(res) {
if (!res.authSetting['scope.writePhotosAlbum']) {
/* 打开设置的方法 */
opensit();
}
}
});
}
});
/* 授权提示 ,这里就是重复提示用户去授权*/
function opensit() {
uni.showModal({
content: '由于您还没有允许保存图片到您相册里,这无法进行分享操作点击确定去允许授权',
success: function(res) {
if (res.confirm) {
/* 这个就是打开设置的API*/
uni.openSetting({
success(res) {
console.log(res.authSetting);
}
});
} else if (res.cancel) {
uni.showModal({
cancelText: '依然取消',
confirmText: '重新授权',
content: '很遗憾你点击了取消,这将无法进行分享操作,请慎重考虑',
success: function(res) {
if (res.confirm) {
uni.openSetting({
success(res) {
console.log(res.authSetting);
}
});
} else if (res.cancel) {
console.log('用户不授权');
}
}
});
}
}
});
}
/* 特别注意要先获取图片信息在进行保存,不让保存不了 */
function img() {
/* 我这里要保存多张图片,一张的话就可以取消这些,具体看你的需求 */
if (num > len) {
return false;
}
/* 获取图片信息 */
uni.getImageInfo({
src: obj[num],
success: function(image) {
console.log(image);
/* 保存图片到相册 */
uni.saveImageToPhotosAlbum({
filePath: image.path,
success: function() {
console.log('save success');
if (num == len) {
uni.showModal({
title: '保存成功',
content: '图片已成功保存到相册,快去分享到您的圈子吧',
showCancel: false
});
}
},
complete(res) {
console.log(res);
}
});
}
});
num++;
img();
}
网友评论