Files
mini-programs/src/utils/wx_helper.ts
2026-02-14 12:59:21 +08:00

49 lines
1.1 KiB
TypeScript

import Taro from "@tarojs/taro";
export function saveImage(url) {
// 下载网络图片,返回本地 temp 文件
const download = () => {
return Taro.downloadFile({ url }).then(res => {
if (res.statusCode === 200) {
return res.tempFilePath
}
throw new Error("图片下载失败")
})
}
const save = async () => {
try {
const filePath = await download()
await Taro.saveImageToPhotosAlbum({ filePath })
Taro.showToast({ title: "保存成功" })
} catch (e) {
console.warn(e)
Taro.showToast({ title: "图片保存失败", icon: "none" })
}
}
Taro.getSetting().then(res => {
const authorized = res.authSetting["scope.writePhotosAlbum"]
if (!authorized) {
Taro.authorize({
scope: "scope.writePhotosAlbum",
success: () => {
save()
},
fail: () => {
Taro.showModal({
title: "提示",
content: "需要开启相册权限才能保存图片",
success: (r) => {
if (r.confirm) Taro.openSetting()
}
})
}
})
} else {
save()
}
})
}