微信小程序实现点击保存图片
wxml代码
<view class='title'>点击图片保存图片</view>
<image class='img' data-src="http://img2.imgtn.bdimg.com/it/u=3507713655,931555131&fm=26&gp=0.jpg" bindtap="downLoadImage" src='http://img2.imgtn.bdimg.com/it/u=3507713655,931555131&fm=26&gp=0.jpg'></image>
<i-message id="message" />
js代码
//index.js
//获取应用实例
const app = getApp()
const { $Message } = require('../../components/iview-weapp/base/index');
Page({
data: {
},
onLoad: function () {
},
//点击事件
downLoadImage(e){
this.downloadFileImages(e.target.dataset.src);
},
//是否授权
downloadFileImages(images) {
let t = this;
wx.getSetting({
success(res) {
if (res.authSetting['scope.writePhotosAlbum'] == true) {
t.retrundownloadFileImage(images);
} else {
if (res.authSetting['scope.writePhotosAlbum'] == false) {
$Message({
content: '您拒绝访问相册,请在小程序授权页面重新授权。',
});
return;
}
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
t.retrundownloadFileImage(images);
}
})
}
}
})
},
//保存图片
retrundownloadFileImage(images) {
wx.downloadFile({
url: images,
header: {},
success: function (res) {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function (res) {
$Message({
content: '保存成功,请前往相册查看。',
});
}.bind(this),
fail: function (res) {
$Message({
content: '保存失败。',
});
}.bind(this),
complete: function (res) { console.log(321);},
})
}.bind(this),
fail: function (res) { },
complete: function (res) {
console.log(123);
}.bind(this),
});
},
})