uni-app保存图片到相册

355 阅读1分钟

保存多张图片

一定要写入AppID 养成习惯

image.png 本地资源网络资源都可以

<template>
	<view class="container">
		<!-- 保存多张图片 -->
		<button @click="savePhoto(0)">点击下载图片</button>
	</view>
</template>
<script>
export default {
		data() {
			return {
				imagePaths: ['../../static/c1.png', '../../static/c2.png', '../../static/c3.png']
			}
		},
		methods: {
			savePhoto(index) {
				let that = this;
				uni.showLoading({
					title: "保存中...",
					icon: "loading",
				});
				if (index >= this.imagePaths.length) {
					console.log('所有图片保存完成');
					uni.hideLoading();
					return;
				}
				uni.getImageInfo({
					src: this.imagePaths[index],
					success: function(image) {
						uni.saveImageToPhotosAlbum({
							filePath: image.path,
							success: function(res) {

								that.savePhoto(index + 1)
							},
							fail(error) {

								console.log(error);
								that.savePhoto(index + 1);
							},
						});
					},
					fail(error) {
						console.log(error);
					},
				})
			},


		}

	}
</script>

授权保存

本地资源网络资源都可以

<template>
	<view>
		<!-- 授权保存 -->
		<button type="success" @click="saveImg">授权保存</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imagePaths: ['../../static/c1.png', '../../static/c2.png', '../../static/c3.png']
			}
		},
		methods: {
			// 图片授权保存
			saveImg() {
				let that = this;
				// 向用户发起授权请求
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success: () => {
						// 已授权
						// console.log('授权成功')
						that.downLoadImg();
					},
					fail: () => {
						// 拒绝授权,获取当前设置
						uni.getSetting({
							success: (result) => {
								if (!result.authSetting['scope.writePhotosAlbum']) {
									that.isAuth()
								}
							}
						});
					}
				})
			},
			downLoadImg() {
				//下载图片资源至本地,返回文件的本地临时路径
				uni.downloadFile({
					url: this.imgUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							//保存图片至相册
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									uni.showToast({
										title: "保存成功",
										icon: "none"
									});
								},
								fail: function() {
									uni.showToast({
										title: "保存失败,请稍后重试",
										icon: "none"
									});
								}
							});
						}
					}
				})
			},
			//引导用户开启权限
			isAuth() {
				uni.showModal({
					content: '由于您还没有允许保存图片到您相册里,无法进行保存,请点击确定允许授权',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting({
								success: (result) => {
									console.log(result.authSetting);
								}
							});
						}
					}
				});
			},


		}

	}
</script>

授权保存实现多张保存和上面写的多张保存demo逻辑相同事件回调即可

image.png