前言:
最近在公司完成一个小程序的时候需要实现一个功能:点击按钮获取用户相册权限,将图片下载到用户本地相册,经过了好几次的尝试最终算是实现了。将总结的经验在这里分享给小伙伴们。
实现方式:
//.wxml文件
<view class="canvas-box">
//注意:一定要添加:type="2d"
<canvas id="posterCanvas"canvas-id="posterCanvas" type="2d"></canvas>
<view class="upload_btn" bindtap="onSaveSuccess"></view>
</view>
//.js文件
data: {
urlSrc: "",
},
// 保存图片
onSaveSuccess() {
const query = wx.createSelectorQuery().in(this);
query
.select("#posterCanvas")
.fields({ node: true, size: true })
.exec((res) => {
if (res[0] && res[0].node) {
const canvas = res[0].node;
// 将 canvas 内容导出为临时文件
wx.canvasToTempFilePath({
canvas,
success: (res) => {
if (res.tempFilePath) {
this.setData({
urlSrc: res.tempFilePath,
});
this.saveCard(res.tempFilePath);
} else {
wx.showToast({
title: "导出失败,请重试",
icon: "none",
});
}
},
fail: (err) => {
wx.showToast({
title: "导出失败,请重试",
icon: "none",
});
},
});
} else {
wx.showToast({
title: "未找到 canvas 节点",
icon: "none",
});
}
});
},
saveCard: function (img) {
let that = this;
var imgSrc = img;
//获取相册授权
wx.getSetting({
success(res) {
if (!res.authSetting["scope.writePhotosAlbum"]) {
wx.authorize({
scope: "scope.writePhotosAlbum",
success() {
that.img(imgSrc);
},
});
} else {
that.img(imgSrc);
}
},
});
},
img: function (imgSrc) {
var imgSrc = imgSrc;
// wx.downloadFile({
// url: imgSrc,
// success: function (res) {
wx.saveImageToPhotosAlbum({
filePath: imgSrc,
success: function (data) {
wx.showToast({
title: "保存成功",
duration: 2000,
});
},
fail: function (err) {
if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
wx.openSetting({
success(settingdata) {
if (settingdata.authSetting["scope.writePhotosAlbum"]) {
wx.showToast({
title: "图片已保存",
icon: "none",
duration: 2000,
});
console.log(
"获取权限成功,给出再次点击图片保存到相册的提示。"
);
} else {
console.log("获取权限失败,给出不给权限就无法正常使用的提示");
}
},
});
}
},
});
// },
// fail: function (err) {
// console.log(err, "进入wx.downloadFile错误分支");
// },
// });
},
注意事项:
不使用wx.downloadFile方法的原因是:使用 wx.canvasToTempFilePath方法将会导出一个http://temp....png的图片,使用wx.downloadFile方法将会报错:downloadFile:fail url not in domain list,关于解决这个报错请看我的另一篇博客:解决微信小程序下载图片报错:downloadFile:fail url not in domain list。众所周知,微信公众平台的downloadFile合法域名只能配置以https://开头的域名,既然已经获得了这个文件地址就可以直接调用 wx.saveImageToPhotosAlbum方法,将其直接保存在用户本地相册