赞
踩
长按
,一个是保存图片到本地
。bindlongpress
事件wx.saveImageToPhotosAlbum()
1、需要先授权,调用wx.getSetting()
方法
2、保存的图片路径参数,不支持网络路径,而在我们渲染页面时,用到的图片有很大可能是网络路径,这时候我们需要先把网络路径转为可用的本地路径,wx.getImageInfo()
方法可以满足需要
1、长按后直接保存未免潦草了些,考虑到用户体验,加入wx.showActionSheet()
2、如果用户拒绝授权 或者 以前拒绝过授权,这时候也应该给他提示,或者展示再次打开授权的入口
<image src="{{url}}" data-url="{{url}}" bindlongpress="saveImage"></image>
// 长按保存功能--授权部分 saveImage (e) { let _this = this wx.showActionSheet({ itemList: ['保存到相册'], success(res) { let url = e.currentTarget.dataset.url; wx.getSetting({ success: (res) => { if (!res.authSetting['scope.writePhotosAlbum']) { wx.authorize({ scope: 'scope.writePhotosAlbum', success: () => { // 同意授权 _this.saveImgInner(url); }, fail: (res) => { console.log(res); wx.showModal({ title: '保存失败', content: '请开启访问手机相册权限', success(res) { wx.openSetting() } }) } }) } else { // 已经授权了 _this.saveImgInner(url); } }, fail: (res) => { console.log(res); } }) }, fail(res) { console.log(res.errMsg) } }) }, // 长按保存功能--保存部分 saveImgInner (url) { wx.getImageInfo({ src: url, success: (res) => { let path = res.path; wx.saveImageToPhotosAlbum({ filePath: path, success: (res) => { console.log(res); wx.showToast({ title: '已保存到相册', }) }, fail: (res) => { console.log(res); } }) }, fail: (res) => { console.log(res); } }) },
文章写的比较正序,参考的是这篇倒序文章,喜欢倒序的筒子们可以去看下这篇: https://www.jianshu.com/p/e592e9b28192
到这里文章差不多就结束了。
————————————————————————————————————————
<image src="{{url}}" data-url="{{url}}" bindlongpress="saveImage"></image>
// 长按保存功能 saveImage (e) { const url = e.currentTarget.dataset.url; const { saveImage1, saveImage2, saveImage3, saveImage4 } = this saveImage1(url).then(saveImage2).then(saveImage3).then(saveImage4) }, // 吊起 actionsheet saveImage1 (url) { const p1 = new Promise((resolve, reject) => { wx.showActionSheet({ itemList: ['保存到相册'], success: res => { resolve(url) }, fail: err => { reject(err) } }) }) return p1 }, // 授权 saveImage2 (url) { const p2 = new Promise((resolve, reject) => { wx.getSetting({ success: settings => { if (!settings.authSetting['scope.writePhotosAlbum']) { wx.authorize({ scope: 'scope.writePhotosAlbum', success: () => { // 同意授权 resolve(url) }, fail: () => { wx.showModal({ title: '保存失败', content: '请开启访问手机相册权限', success: () => { wx.openSetting() } }) reject() } }) } else { // 已经有权限了 resolve(url) } } }) }) return p2 }, // 转换图片格式为本地路径 saveImage3 (url) { const p3 = new Promise((resolve, reject) => { wx.getImageInfo({ src: url, success: res => { resolve(res.path) }, fail: () => { reject() } }) }) return p3 }, // 保存 saveImage4 (path) { const p4 = new Promise((resolve, reject) => { wx.saveImageToPhotosAlbum({ filePath: path, success: () => { wx.showToast({ title: '已保存到相册', }) }, fail: err => { console.log(err) } }) }) return p4 },
然后这才算是结束!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。