daShangDao_psiWebApp/src/utils/uploadLivingPicture.ts
97694731 939d55c950
Some checks failed
CI / build (18.x) (push) Failing after 1m34s
CI / build (20.x) (push) Failing after 34s
CI / deploy-preview (push) Has been skipped
CI / lint (push) Failing after 34s
CI / test (push) Failing after 34s
CI / security (push) Failing after 35s
6.22lct bug 修改
2026-06-22 17:10:51 +08:00

69 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 上传图片到外部图床living-picture 服务)
* PUT https://shxy.image.yushutx.com/living-picture/{pictureName}
*
* 支持传入 File 对象或 base64 字符串。
* 原函数位于 src/components/wave/camera.vue提取为独立工具函数以便复用。
*/
/**
* 将 File 对象转为 base64 字符串
*/
function fileToBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result as string)
reader.onerror = () => reject(new Error('文件读取失败'))
reader.readAsDataURL(file)
})
}
/**
* 上传图片到 living-picture 图床
* @param file - File 对象或 base64 数据字符串(含 data:image/...;base64, 前缀)
* @param pictureName - 上传后的文件名(不含路径),如 'abc123.jpg'
* @param isbn - ISBN仅用于日志可选
* @returns 上传后的完整图片 URL
*/
export async function uploadLivingPicture(
file: File | string,
pictureName: string,
isbn?: string
): Promise<string> {
// 若传入 File 对象,先转为 base64
let base64Data: string
if (typeof file === 'string') {
base64Data = file
} else {
base64Data = await fileToBase64(file)
}
console.log('[上传实拍] 开始上传, 文件名:', pictureName)
// 去掉 base64 头,转为二进制
const base64 = base64Data.replace(/^data:image\/\w+;base64,/, '')
const binaryString = atob(base64)
const bytes = new Uint8Array(binaryString.length)
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i)
}
const blob = new Blob([bytes], { type: 'image/jpeg' })
const url = `https://shxy.image.yushutx.com/living-picture/${pictureName}`
console.log('[上传实拍] PUT URL:', url, '| Blob大小:', blob.size)
const resp = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'image/jpeg' },
body: blob
})
console.log('[上传实拍] 响应状态:', resp.status, resp.statusText)
if (!resp.ok) {
throw new Error(`实拍图片上传失败 [${isbn || 'unknown'}]: HTTP ${resp.status}`)
}
console.log(`实拍图片上传成功 [${isbn || 'unknown'}]`)
return url
}