uniapp实现app端和微信小程序端图片保存到本地,其它平台未测过,原理类似。
微信小程序端主要是权限需要使用button的开放能力来反复调起,代码如下:
首先是条件编译两个平台的按钮组件:
<!-- #ifndef MP-WEIXIN -->
<view class="purple_btn btn_box" @click="saveImgToLocal">保存到相册</view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view v-if="openSettingBtnHidden" class="purple_btn btn_box" @click="saveEwm">保存到相册</view>
<button v-else class="purple_btn btn_box" hover-class="none" open-type="openSetting" @opensetting='handleSetting'>保存到相册</button>
<!-- #endif -->
js部分如下:
var _self;
export default{
data(){
return {
openSettingBtnHidden: true,//是否授权
ewmImg:""//这是要保存的图片
}
},
onLoad(opt) {
_self = this;
},
components:{
},
methods:{
//微信小程序保存到相册
handleSetting(e){
if (!e.detail.authSetting['scope.writePhotosAlbum']) {
_self.openSettingBtnHidden = false;
} else {
_self.openSettingBtnHidden = true;
}
},
saveEwm:function(e){
//获取相册授权
uni.getSetting({
success(res) {
if (!res.authSetting['scope.writePhotosAlbum']) {
uni.authorize({
scope: 'scope.writePhotosAlbum',
success() {
//这里是用户同意授权后的回调
_self.saveImgToLocal();
},
fail() {//这里是用户拒绝授权后的回调
_self.openSettingBtnHidden=false
}
})
} else {//用户已经授权过了
_self.saveImgToLocal();
}
}
})
},
saveImgToLocal:function(e){
uni.showModal({
title: '提示',
content: '确定保存到相册吗',
success: function (res) {
if (res.confirm) {
uni.downloadFile({
url: _self.ewmImg,//图片地址
success: (res) =>{
if (res.statusCode === 200){
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function() {
uni.showToast({
title: "保存成功",
icon: "none"
});
},
fail: function() {
uni.showToast({
title: "保存失败",
icon: "none"
});
}
});
}
}
})
} else if (res.cancel) {
}
}
});
}
}
}
tips:
特别要注意的是权限问题,小程序中下载图片还得要添加域名白名单,不然无法下载