Blame view

美国版/Food Labeling Management Platform/src/services/imageUploadService.ts 4.97 KB
3af4878d   杨鑫   产品 标签 关联
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
  /**
   * 平台端图片上传:对接 `/api/app/picture/category/upload`(见《平台端Categories图片上传接口说明》)。
   * 返回的 `url` 为相对路径(如 `/picture/category/xxx.png`),保存到业务字段;展示时用 `resolvePictureUrlForDisplay`。
   */
  
  /** 与文档一致:POST multipart,字段 file + 可选 subDir */
  export const PICTURE_CATEGORY_UPLOAD_PATH = "/api/app/picture/category/upload";
  
  function joinBaseAndPath(baseUrl: string, path: string): string {
    const b = baseUrl.replace(/\/$/, "");
    const p = path.startsWith("/") ? path : `/${path}`;
    return `${b}${p}`;
  }
  
  /** 与后端限制一致:5MB */
  export const PICTURE_UPLOAD_MAX_BYTES = 5 * 1024 * 1024;
  
  export type UploadImageOptions = {
    /** 可选子目录,如 `category`、`product`;禁止包含 `..` */
    subDir?: string;
    signal?: AbortSignal;
  };
  
  function getApiBaseUrl(): string {
    return (import.meta.env.VITE_API_BASE_URL as string | undefined)?.replace(/\/$/, "") ?? "http://localhost:19001";
  }
  
  function getToken(): string | null {
    try {
      return localStorage.getItem("access_token") ?? localStorage.getItem("token");
    } catch {
      return null;
    }
  }
  
  function pickUrlFromPayload(x: unknown): string | null {
    if (typeof x === "string" && x.trim()) {
      const t = x.trim();
      if (/^https?:\/\//i.test(t) || t.startsWith("/") || t.startsWith("data:")) return t;
    }
    if (!x || typeof x !== "object") return null;
    const o = x as Record<string, unknown>;
    for (const k of ["url", "Url", "fileUrl", "FileUrl", "imageUrl", "ImageUrl", "path", "Path"]) {
      const v = o[k];
      if (typeof v === "string" && v.trim()) return v.trim();
    }
    return null;
  }
  
  function unwrapData(payload: unknown): unknown {
    if (!payload || typeof payload !== "object") return payload;
    const o = payload as Record<string, unknown>;
    if ("data" in o && o.data !== undefined) return o.data;
    if ("result" in o && o.result !== undefined) return o.result;
    return payload;
  }
  
  function messageFromErrorPayload(payload: unknown, status: number): string {
    if (payload && typeof payload === "object") {
      const o = payload as Record<string, unknown>;
      const err = o.errors ?? o.Errors;
      if (typeof err === "string" && err.trim()) return err.trim();
      const nested = o.error as { message?: string } | undefined;
      if (nested && typeof nested.message === "string" && nested.message.trim()) return nested.message.trim();
    }
    return `Upload failed (${status})`;
  }
  
  /**
   * 将保存的地址转为浏览器可请求的绝对 URL(相对 `/picture/...` 会拼上 API 宿主)。
   */
  export function resolvePictureUrlForDisplay(stored: string): string {
    const s = (stored ?? "").trim();
    if (!s) return "";
    if (s.startsWith("data:")) return s;
    if (/^https?:\/\//i.test(s)) return s;
    const base = getApiBaseUrl();
    return s.startsWith("/") ? `${base}${s}` : `${base}/${s}`;
  }
  
  function validateFile(file: File): void {
    if (file.size > PICTURE_UPLOAD_MAX_BYTES) {
      throw new Error("Image must be 5 MB or smaller.");
    }
    const okMime = /^(image\/(jpeg|png|webp|gif))$/i.test(file.type);
    const okExt = /\.(jpe?g|png|webp|gif)$/i.test(file.name);
    if (!okMime && !okExt) {
      throw new Error("Only JPG, PNG, WebP, and GIF are allowed.");
    }
  }
  
  function readFileAsDataUrl(file: File): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        const r = reader.result;
        if (typeof r === "string") resolve(r);
        else reject(new Error("Failed to read file."));
      };
      reader.onerror = () => reject(new Error("Failed to read file."));
      reader.readAsDataURL(file);
    });
  }
  
  /**
   * 上传图片;返回后端 `PictureUploadOutputDto.url`(相对路径,可写入 CategoryPhotoUrl 等字段)。
   */
  export async function uploadImageFile(file: File, options?: UploadImageOptions): Promise<string> {
    if (import.meta.env.VITE_IMAGE_UPLOAD_MOCK === "true") {
      validateFile(file);
      return readFileAsDataUrl(file);
    }
  
    validateFile(file);
  
    const sub = options?.subDir?.trim();
    if (sub && sub.includes("..")) {
      throw new Error("Invalid subDir.");
    }
  
    const uploadUrl = joinBaseAndPath(getApiBaseUrl(), PICTURE_CATEGORY_UPLOAD_PATH);
  
    const fd = new FormData();
    fd.append("file", file);
    if (sub) fd.append("subDir", sub);
  
    const headers: Record<string, string> = {};
    const token = getToken();
    if (token) headers.Authorization = `Bearer ${token}`;
  
    const res = await fetch(uploadUrl, {
      method: "POST",
      body: fd,
      headers,
      signal: options?.signal,
    });
  
    const text = await res.text();
    let payload: unknown = text;
    try {
      payload = text ? JSON.parse(text) : null;
    } catch {
      payload = text;
    }
  
    if (!res.ok) {
      throw new Error(messageFromErrorPayload(payload, res.status));
    }
  
    const inner = unwrapData(payload);
    const url = pickUrlFromPayload(inner) ?? pickUrlFromPayload(payload);
    if (!url) {
      throw new Error("Upload response did not contain a usable image URL.");
    }
    return url;
  }