微信小程序 保存图片和复制文字 功能
1.保存图片,点击保存到手机相册里
拿到服务端返回的图片地址,用户点击按钮保存图片。这个有个小程序相册权限问题。
用户第一次拒绝的权限的时候,需要调用wx.openSeting()打开权限。
这里有个坑:2018年后,wx.openSeting()不能在失败回调里打开,需要在点击按钮时触发:
官方回复:https://developers.weixin.qq.com/community/develop/doc/000cea2305cc5047af5733de751008
所以解决的思路是:
1.每一次进入点击保存图片的页面,在onShow里默认是有权限的,
2.当用户点击保存图片时,拒绝了保存到相册的权限,我们把这个按钮提示为:打开系统保存到相册权限,跳转到wx.openSeting()打开的权限页面。
2.复制文字
这个貌似没有权限问题
3.代码
封装在一个WxUtil.js里:
const saveImg = (imgSrc, cb) => {
wx.downloadFile({
url: imgSrc,
success: function(res) {
console.log(res);
//图片保存到本地
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function(data) {
wx.showToast({
title: '保存成功',
icon: 'none'
})
},
fail: function(err) {
console.log('fail');
//不能直接用 wx.openSetting(),需要执行失败的回调
cb()
},
complete(res) {
console.log(res);
}
})
}
})
}
const copyText = (text) => {
wx.setClipboardData({
data: text,
success(res) {
wx.getClipboardData({
success(res) {
wx.showToast({
icon: 'none',
title: '复制成功'
})
}
})
}
})
}
export { saveImg, copyText }
在page下的页面js里调用saveImg ,在test页面下:
test.wxml:
<view>
<view class="save-btn" bindtap="saveCord" wx:if="{{hasSetting}}">
点我保存二维码
</view>
<view class="save-btn" bindtap="toSetting" wx:else>
请在设置页面打开相册权限
</view>
</view>
test.js:
import { saveImg } from '../../utils/wxUtil.js'
Page({
data: {
//是否有相册权限
hasSetting: true
},
onLoad() {
this.getPageData();
},
onShow() {
this.setData({
hasSetting: true
})
},
saveCord() {
//服务器返回的数据
let imgSrc = this.data.userInfo.code;
saveImg(imgSrc, () => {
this.setData({
hasSetting: false
})
})
},
})

浙公网安备 33010602011771号