Skip to content

Commit 030dcea

Browse files
YuvalYuval
authored andcommitted
fix(files): derive file name from MIME type for uploads
1 parent 7a3d7e2 commit 030dcea

1 file changed

Lines changed: 21 additions & 1 deletion

File tree

03-Client/src/app/services/api/files.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,26 @@ interface UploadResult {
1515
data: { url: string };
1616
}
1717

18+
const MIME_TO_EXT: Record<string, string> = {
19+
"image/jpeg": ".jpg",
20+
"image/jpg": ".jpg",
21+
"image/png": ".png",
22+
"image/webp": ".webp",
23+
};
24+
25+
// browser-image-compression and mobile capture sometimes produce a File with
26+
// no name or no extension. The server's extension check rejects those even
27+
// when the bytes are a valid JPEG, so we derive a name from the MIME type.
28+
function ensureFileName(file: File): string {
29+
const name = file.name ?? "";
30+
const hasAllowedExt = /\.(jpe?g|png|webp)$/i.test(name);
31+
if (hasAllowedExt) return name;
32+
33+
const ext = MIME_TO_EXT[file.type?.toLowerCase() ?? ""] ?? ".jpg";
34+
const base = name.replace(/\.[^.]+$/, "") || `upload-${Date.now()}`;
35+
return `${base}${ext}`;
36+
}
37+
1838
/**
1939
* Upload an image file to the backend.
2040
* Returns the URL of the stored file.
@@ -23,7 +43,7 @@ export async function uploadImage(file: File): Promise<string> {
2343
const token = localStorage.getItem("accessToken");
2444

2545
const formData = new FormData();
26-
formData.append("file", file);
46+
formData.append("file", file, ensureFileName(file));
2747

2848
const res = await fetch(`${API_BASE}/files/upload`, {
2949
method: "POST",

0 commit comments

Comments
 (0)