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

相关API

saveimagetophotosalbum

authorize


步骤

  • 判断用户是否已授权,已授权返回成功,执行保存图片到相册;
  • 如果用户拒绝授权,再次点击保存图片时,引导用户开启权限;

js文件

根据自身需求调整,这里放在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
<template>
	<button class="saveBtn white" @click="savePosterTap">保存至相册</button>
</template>

js
savePosterTap() {
    app.globalData.downLoadUrl = this.$util.img(this.posterUrl); // url
    
    this.saveImage();
},
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐