根据自身需求调整,这里放在js文件[download.js],方便调用
const app = getApp()
export default {
methods: {
/**
* 保存图片
*/
saveImage() {
let that = this;
// 向用户发起授权请求
uni.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
// 已授权
that.downLoadImg();
},
fail: () => {
// 拒绝授权,获取当前设置
uni.getSetting({
success: (result) => {
if (!result.authSetting['scope.writePhotosAlbum']) {
that.isAuth()
}
}
});
}
})
},
/**
* 下载资源,保存图片到系统相册
*/
downLoadImg() {
uni.showLoading({
title: '加载中'
});
uni.downloadFile({
url: app.globalData.downLoadUrl,
success: (res) => {
uni.hideLoading();
if (res.statusCode === 200) {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function() {
uni.showToast({
title: "保存成功",
icon: "none"
});
},
fail: function() {
uni.showToast({
title: "保存失败,请稍后重试",
icon: "none"
});
}
});
}
},
fail: (err) => {
uni.showToast({
title: "失败啦",
icon: "none"
});
}
})
},
/*
* 引导用户开启权限
*/
isAuth() {
uni.showModal({
content: '由于您还没有允许保存图片到您相册里,无法进行保存,请点击确定允许授权',
success: (res) => {
if (res.confirm) {
uni.openSetting({
success: (result) => {
console.log(result.authSetting);
}
});
}
}
});
},
}
}
<template>
<button class="saveBtn white" @click="savePosterTap">保存至相册</button>
</template>
savePosterTap() {
app.globalData.downLoadUrl = this.$util.img(this.posterUrl); // url
this.saveImage();
},