开发微信小程序,将图片下载到相册的方法,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();
	}
}
相关推荐
游戏开发爱好者81 天前
苹果 App 上架流程,结合 Xcode、CI 等常见工具
macos·ios·ci/cd·小程序·uni-app·iphone·xcode
前端老白1 天前
webview在微信小程序中,安卓加载失败,IOS正常加载
android·ios·微信小程序·webview
2501_915106321 天前
用 HBuilder 上架 iOS 应用时如何管理Bundle ID、证书与描述文件
android·ios·小程序·https·uni-app·iphone·webview
2501_915909061 天前
资源文件混淆在 iOS 应用安全中的实际价值
android·安全·ios·小程序·uni-app·iphone·webview
2501_915918411 天前
iOS App 性能测试中常被忽略的运行期问题
android·ios·小程序·https·uni-app·iphone·webview
多仔ヾ1 天前
微信小程序开发实战之 03-微信小程序页面交互
微信小程序
狮子也疯狂1 天前
【鸿蒙小程序】| 鸿蒙系统中的元服务创新与实践
小程序·notepad++·harmonyos
汝生淮南吾在北2 天前
SpringBoot3+Vue3小区物业报修系统+微信小程序
微信小程序·小程序·vue·毕业设计·springboot·课程设计·毕设
静待雨落2 天前
如何在Taro项目中使用axios
微信小程序·taro
前端小黑屋2 天前
小程序直播挂件Pendant问题
前端·微信小程序·直播