一、实现思路

1.先调用getSetting方法去获取用户的当前设置。判断是否授权保存图片。

2.如果没有开启保存权限,则调用authorize方法 传入参数 开启权限。

3.开启权限后调用getImageInfo方法,获取图片path。

4.获取图片path后,调用saveImageToPhotosAlbum方法,将图片保存到本地

二、具体实现代码

可供测试的下载图片链接:

https://img-blog.csdnimg.cn/fcc22710385e4edabccf2451d5f64a99.jpeg

具体代码:

const downloadPic = (imageTempPath : any) => {
		uni.getSetting({
			complete(res) {
				console.log(res.authSetting,"授权信息");
				if (res.authSetting['scope.writePhotosAlbum']) {
					console.log(res.authSetting['scope.writePhotosAlbum'],"是否已经授权");
					uni.getImageInfo({
						src: imageTempPath,
						fail(error) {
							console.log(error);
						},
						success(result) {
							console.log(result);
							if (result.path) {
								uni.saveImageToPhotosAlbum({
									filePath: result.path,
								}).then((getImageInfoResult) => {
									if (getImageInfoResult.errMsg === 'saveImageToPhotosAlbum:ok') {
										uni.showToast({
											title: "已成功保存至相册!",
											duration: 1000
										})
									} else {
										uni.showToast({
											title: "图片保存失败!",
											duration: 1000
										})
									}
								});
							}
						},
					});


				} else {
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
					}).then(() => {
						uni.getImageInfo({
							src: imageTempPath,
							success(result) {
								if (result.path) {
									uni.saveImageToPhotosAlbum({
										filePath: result.path,
									}).then((getImageInfoResult) => {
										if (
											getImageInfoResult.errMsg === 'saveImageToPhotosAlbum:ok'
										) {
											uni.showToast({
												title: "已成功保存至相册!",
												duration: 1000
											})
										} else {
											uni.showToast({
												title: "图片保存失败!",
												duration: 1000
											})
										}

									})
								}
							}

						})
					}).catch((err) => {
						console.log(err);
					});
				}

			}
		})

	}

更多推荐