开发微信小程序,将图片下载到相册的方法,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();
	}
}
相关推荐
weixin_lynhgworld2 小时前
从闲置到珍宝:旧物回收小程序系统重塑物品价值
小程序·旧物回收
2501_916007477 小时前
iOS App 上架实战 从内测到应用商店发布的全周期流程解析
android·ios·小程序·https·uni-app·iphone·webview
小小怪下士_---_12 小时前
uniapp开发微信小程序自定义导航栏
前端·vue.js·微信小程序·小程序·uni-app
摸着石头过河的石头14 小时前
小程序调试全攻略:微信/支付宝避坑指南,小白也能一次通关
前端·微信小程序
fakaifa1 天前
点大餐饮独立版系统源码v1.0.3+uniapp前端+搭建教程
小程序·uni-app·php·源码下载·点大餐饮·扫码点单
Dignity_呱1 天前
如何在不发版时,实现小程序的 AB 测试?
前端·面试·微信小程序
说私域1 天前
基于开源 AI 大模型 AI 智能名片 S2B2C 商城小程序视角下的企业组织能力建设与破圈升级
人工智能·小程序
fakaifa2 天前
【最新版】CRMEB Pro版v3.4系统源码全开源+PC端+uniapp前端+搭建教程
人工智能·小程序·uni-app·php·crmeb·源码下载·crmebpro
2501_915918412 天前
iOS 应用上架全流程实践,从开发内测到正式发布的多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview
上海云盾第一敬业销售2 天前
小程序被爬虫攻击,使用waf能防护吗?
爬虫·小程序