微信小程序长按保存图片到系统相册

微信小程序长按保存图片到系统相册

pages\index\index.wxml

1
2
3
<view class="container">
<image src="https://cdn.hongfs.cn/avatar.png" data-src="https://cdn.hongfs.cn/avatar.png" bindlongpress="handleImageSave"></image>
</view>

pages\index\index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
handleImageSave: function (e) {
const dataset = e.target.dataset;

if (!dataset.hasOwnProperty('src') || !dataset.src) {
return wx.showToast({
title: '获取图片地址失败',
icon: 'none',
});
}

const url = dataset.src;

// 进行保存相册授权,如果已授权过会直接进入 success
return wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
// 下载图片资源
return wx.downloadFile({
url: url,
success(res) {
// 非 200 状态码
if (res.statusCode !== 200) {
return wx.showToast({
title: '下载图片资源失败',
icon: 'none',
});
}

// 把下载的临时文件保存到系统相册
return wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success () {
return wx.showToast({
title: '保存成功',
icon: 'success',
});
},
fail () {
return wx.showToast({
title: '保存文件失败',
icon: 'none',
});
},
});
}
});
},
fail() {
return wx.showToast({
title: '保存相册授权失败',
icon: 'none',
});
},
});
},
往上