uniapp+vue2+h5图片下载保存,微信浏览器、非微信浏览器

发布于:2025-06-11 ⋅ 阅读:(28) ⋅ 点赞:(0)

小程序端

onDown() {
	// 检查相册权限
	uni.authorize({
		scope: 'scope.writePhotosAlbum',
		success: () => {
			this.downloadImage();
		},
		fail: () => {
			uni.showToast({
				title: "请授权相册权限",
				icon: "none"
			});
		}
	});
},
downloadImage() {
	common.request('post', '/agent/Managestart/downQrcode', {
		device_id: this.device_id
	}).then(res => {
		if (res.code === 1) {
			uni.downloadFile({
				url: res.data,
				success: (downloadRes) => {
					if (downloadRes.statusCode === 200) {
						uni.saveImageToPhotosAlbum({
							filePath: downloadRes.tempFilePath,
							success: () => {
								uni.showToast({
									title: "保存成功"
								});
							},
							fail: () => {
								uni.showToast({
									title: "保存失败",
									icon: "none"
								});
							}
						});
					}
				}
			});
		}
	});
}

微信打开

onDown() {
	common.request('post', '/agent/Managestart/downQrcode', {
		device_id: this.device_id
	}).then(res => {
		if (res.code == 1) {
			const imageData = common.image(res.data);

			// 检测是否是微信浏览器
			const isWeixin = /MicroMessenger/i.test(navigator.userAgent);
			if (isWeixin) {
				// 微信浏览器:强制跳转到图片 URL
				window.location.href = imageData;
			} else {
				// 非微信浏览器:通用下载方式
				const link = document.createElement("a");
				link.href = imageData;
				link.download = "qrcode.png";
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
			}
		} else {
			uni.showToast({
				title: "获取图片失败",
				icon: "none"
			});
		}
	}).catch(() => {
		uni.showToast({
			title: "网络异常",
			icon: "none"
		});
	});
},