wxml:
<view class="container">
<view class='page-section'>
<view class="saveImage" style="padding:0 8px;">
<view class="img_box" style="text-align:center;">
<image src="这里写合法域名下的图片路径(https开头)" style="width:93px;height:38px;margin-top:10px"></image>
</view>
<button class="weui-btn" type="primary" bindtap='onSavePicClick' data-img="这里写合法域名下的图片路径(https开头)">点击保存图片</button>
</view>
</view>
</view>
js:
Page({
downloadImage: function (imageUrl) {
// 下载文件
wx.downloadFile({
url: imageUrl,
success: function (res) {
console.log("下载文件:success");
console.log(res);
// 保存图片到系统相册
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
console.log("保存图片:success");
wx.showToast({
title: '保存成功',
});
},
fail(res) {
console.log("保存图片:fail");
console.log(res);
}
})
},
fail: function (res) {
console.log("下载文件:fail");
console.log(res);
}
})
},
onSavePicClick: function (e) {
var that=this;
console.log("onSavePicClick");
console.log(e);
var downloadUrl = e.currentTarget.dataset.img ;
console.log("downloadUrl=" + downloadUrl);
if (!wx.saveImageToPhotosAlbum) {
wx.showModal({
title: '提示',
content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
})
return;
}
// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope
wx.getSetting({
success(res){
console.log("getSetting: success");
if (!res.authSetting['scope.writePhotosAlbum']) {
console.log("1-没有授权《保存图片》权限");
// 接口调用询问
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
console.log("2-授权《保存图片》权限成功");
that.downloadImage(downloadUrl);
},
fail() {
// 用户拒绝了授权
console.log("2-授权《保存图片》权限失败");
// 打开设置页面
wx.openSetting({
success: function (data) {
console.log("openSetting: success");
},
fail: function (data) {
console.log("openSetting: fail");
}
});
}
})
} else {
console.log("1-已经授权《保存图片》权限");
that.downloadImage(downloadUrl)
}
},
fail(res) {
console.log("getSetting: fail");
console.log(res);
}
})
},
})
效果图: