新增: 跨端图片上传(file.1216.top URL 优先,失败回退 base64,协议对齐)

This commit is contained in:
lxy
2026-08-08 14:19:26 +08:00
parent 4ce6a859e7
commit d19784a414
9 changed files with 247 additions and 42 deletions
+38
View File
@@ -0,0 +1,38 @@
//! 桌面端文件服务上传(file.1216.top)— 图片/文件 → 公开 URL
//!
//! 与小程序端 `apps/df-miniapp/src/utils/fileUpload.ts` 对称:复用 file.1216.top 的
//! `POST /upload`(multipart 'file' + X-Source 头)→ 返回公开 URL。
//! 桌面端是浏览器环境,用 fetch + FormData(区别于小程序 uni.uploadFile)。
//! file.1216.top 已确认 CORS 支持(`Access-Control-Allow-Origin: *`,X-Source 在 allow-headers)。
/** file.1216.top 上传地址(可经 appSettings 'df-file-upload-base' 覆盖) */
export const DEFAULT_FILE_UPLOAD_BASE = 'https://file.1216.top'
/** X-Source 项目标识(文件存 file.1216.top 对应目录,项目隔离) */
export const FILE_UPLOAD_SOURCE = 'devflow-desktop'
export interface UploadResult {
url: string
}
/**
* 上传文件到 file.1216.top,返回公开 URL。失败 reject(调用方回退 base64)。
* 响应结构:`{"result":{"url":"https://..."},"retcode":0,"success":true}`
*/
export async function uploadFile(file: File, base?: string): Promise<UploadResult> {
const uploadBase = base || DEFAULT_FILE_UPLOAD_BASE
const form = new FormData()
form.append('file', file, file.name)
const res = await fetch(`${uploadBase}/upload`, {
method: 'POST',
headers: { 'X-Source': FILE_UPLOAD_SOURCE },
body: form,
})
if (!res.ok) {
throw new Error(`上传失败:HTTP ${res.status}`)
}
const data = (await res.json()) as { result?: { url?: string }; success?: boolean; retcode?: number }
if (data?.success === true && data?.retcode === 0 && data?.result?.url) {
return { url: data.result.url }
}
throw new Error(`上传响应异常:${JSON.stringify(data)}`)
}