mediaUrl.ts
1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* 管理后台展示用:将 /uploads/... 转为浏览器可请求的绝对地址。
* 未配置 VITE_API_BASE 时使用当前页面 origin(开发环境由 Vite 代理 /uploads)。
*/
export function resolveAdminMediaUrl(path: string | null | undefined): string {
const raw = typeof path === "string" ? path.trim() : "";
if (!raw) return "";
if (raw.startsWith("blob:") || raw.startsWith("data:")) {
return "";
}
if (raw.startsWith("http://") || raw.startsWith("https://")) {
return raw;
}
const uploads = raw.startsWith("/uploads/")
? raw
: raw.startsWith("uploads/")
? `/${raw}`
: "";
if (uploads) {
const env = import.meta.env.VITE_API_BASE;
const envBase = typeof env === "string" ? env.trim().replace(/\/+$/, "") : "";
const base =
envBase ||
(typeof window !== "undefined" && window.location?.origin
? window.location.origin.replace(/\/+$/, "")
: "");
return base ? `${base}${uploads}` : uploads;
}
if (raw.startsWith("/") && typeof window !== "undefined" && window.location?.origin) {
return `${window.location.origin.replace(/\/+$/, "")}${raw}`;
}
return raw;
}
/** 持久化字段:去掉浏览器临时地址,避免写入数据库 */
export function sanitizeAvatarForSave(path: string): string {
const t = path.trim();
if (!t || t.startsWith("blob:") || t.startsWith("data:")) {
return "";
}
return t;
}