开发微信小程序,将图片下载到相册的方法,saveImageToPhotosAlbum怎么用

在开发微信小程序的时候,经常能看到小程序里面有下载按钮,如何将小程序中的图片下载到手机相册中那,下面给大家说一下怎么做,代码如何去写。

一、到微信小程序后台开启"用户隐私保护指引"

1.进入小程序后台,侧拉拉到"设置"这一项,再找到"服务内容声明",更新"用户隐私保护",如下图所示:

2.按照如下所示的指引填写即可


注意: 如果不更新隐私保护,是无法获取到存储权限的,这个必须要开启才行。

二、代码实现

javascript 复制代码
//点击下载
const clickDownload = async () => {
	try {
		uni.showLoading({
			title: "下载中...",
			mask: true
		})
		let res = await downPushData();
		if(res.errCode != 0) throw res;			
		// #ifdef MP || APP				
		uni.getImageInfo({
			src: crtWallInfo.value.picurl,
			success: function(res) {					
				var path = res.path;
				uni.saveImageToPhotosAlbum({
					filePath: path,
					success(res) {
						uni.hideLoading();
						uni.showToast({
							title: '保存成功,可去相册查看',
							icon: "none",
							duration:2000
						})							
					},
					fail(err) {
						uni.hideLoading();
						if(err.errMsg == 'saveImageToPhotosAlbum:fail cancel'){
							uni.showToast({
								title: '保存失败,请重新点击下载',
								icon: "none"
							})
							return;
						}							
						uni.showModal({
							title: '提示',
							content: '需要您授权保存相册',
							showCancel: false,
							success:res=>{
								if(res.confirm){
									uni.openSetting({
										success(settingdata) {
											if (settingdata.authSetting['scope.writePhotosAlbum']) {
												uni.showToast({
													title:'获取权限成功',
													icon:"none"
												})													
											}else{
												uni.showToast({
													title:'获取权限失败',
													icon:"none"
												})													
											}
											
										}
									})
								}
							}
						})
					},
					complete(err) {
						
					}
				})
			}
		})
		// #endif

		// #ifdef H5
		//调用预览图片的方法		
		uni.previewImage({
			urls: [crtWallInfo.value.picurl],
			current: 0, //点击图片传过来的下标
			success: (res) => {
				uni.showToast({
					title: '请长按保存',
					icon: "none",
					duration: 2000
				})
			}
		})
		// #endif

	} catch (err) {			
		console.log(err);
		uni.hideLoading();
	}
}
相关推荐
不爱吃饭爱吃菜2 小时前
uniapp微信小程序一键授权登录
前端·javascript·vue.js·微信小程序·uni-app
mon_star°9 小时前
微信答题小程序支持latex公式显示解决方案
微信·小程序
MaCa .BaKa21 小时前
38-日语学习小程序
java·vue.js·spring boot·学习·mysql·小程序·maven
HouGISer21 小时前
副业小程序YUERGS,从开发到变现
前端·小程序
橘子海全栈攻城狮1 天前
【源码+文档+调试讲解】党员之家服务系统小程序1
java·开发语言·spring boot·后端·小程序·旅游
好好的哦1 天前
uni-app小程序登录后…
小程序·uni-app
h_65432102 天前
微信小程序点击按钮跳转链接并显示
微信小程序·小程序
银迢迢2 天前
微信小程序的开发及问题解决
微信小程序·小程序
liyinchi19882 天前
原生微信小程序 textarea组件placeholder无法换行的问题解决办法
微信小程序·小程序
说私域2 天前
基于开源链动2+1模式AI智能名片S2B2C商城小程序的低集中度市场运营策略研究
人工智能·小程序·开源·零售