开发微信小程序,将图片下载到相册的方法,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();
	}
}
相关推荐
racerun6 小时前
小程序导航设置更多内容的实现方法
小程序
说私域6 小时前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
mg6686 小时前
微信小程序入门实例_____快速搭建一个快递查询小程序
微信小程序·小程序
程序员柳7 小时前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
Jyywww12110 小时前
微信小程序学习笔记
笔记·学习·微信小程序
The_era_achievs_hero11 小时前
微信小程序41~50
微信小程序·小程序
走,带你去玩19 小时前
uniapp 微信小程序水印
微信小程序·小程序·uni-app
是一碗螺丝粉19 小时前
🔥 微信H5视频自动播放终极秘籍:WeixinJSBridge竟是官方“通行证”?
微信小程序
一笑code20 小时前
vue/微信小程序/h5 实现react的boundary
微信小程序·vue·react