mediaUrl.ts 1.41 KB
/**
 * 管理后台展示用:将 /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;
}