最近项目中遇到一个需求,就是要保存商品的图片到手机相册,一开始我还以为挺简单的,毕竟文档在哪里,小程序一般都是拿来就用的,可是这个就是不行,遇到提示saveImageToPhotosAlbum:fail file not found问题,最后发现是用户没有授权。解决这个问题又发现小程序又无法保存图片,这明明是同意了为什么还不行,经过研究发现,我没要先获取图片信息在进行保存就可以了。我使用的是uni-app来开发的,如果你用原生小程序开发的话就把uni改成wx吧!在这里我强烈推荐大家使用uni-app来开发小程序。具体什么好处,大伙可以去看看uni-app的文档,好了不多说看代码。
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) {
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();
} |