File size: 1,815 Bytes
67a39f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * FRONTEND SERVICE
 * 
 * This service no longer uses @huggingface/hub directly.
 * It sends files to our local Node.js backend (server.js).
 */

// Use relative URL so Vite proxy can forward it to localhost:3001
const BACKEND_URL = '/api/upload';

interface UploadPayload {
  file: File;
  path: string;
}

/**
 * Uploads a file by sending it to the Node.js backend.
 * 
 * @param payload File and destination path
 * @returns The public URL of the uploaded file
 */
export const uploadFileToHub = async (payload: UploadPayload): Promise<string> => {
  const { file, path } = payload;

  const formData = new FormData();
  // Append text fields BEFORE files is good practice for some parsers
  formData.append('path', path);
  formData.append('file', file);

  try {
    const response = await fetch(BACKEND_URL, {
      method: 'POST',
      body: formData,
    });

    // Handle non-JSON responses (like 404 or 502 from proxy)
    const contentType = response.headers.get("content-type");
    if (!contentType || !contentType.includes("application/json")) {
        throw new Error(`Server returned unexpected ${response.status} ${response.statusText}. Is the backend running?`);
    }

    const data = await response.json();

    if (!response.ok || !data.success) {
      throw new Error(data.error || 'Upload failed on server');
    }

    return data.url;
    
  } catch (err: any) {
    console.error("[FE] API Call Failed:", err);
    const errorMessage = err?.message || "Unknown error";
    // Suggest running the server if connection fails
    if (errorMessage.includes('Failed to fetch') || errorMessage.includes('backend running')) {
        throw new Error("Cannot connect to Backend. Make sure to run 'npm run server' in a separate terminal.");
    }
    throw new Error(errorMessage);
  }
};