69 lines
2.2 KiB
TypeScript
69 lines
2.2 KiB
TypeScript
/**
|
||
* 上传图片到外部图床(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
|
||
}
|