Skip to content

Commit 4e87265

Browse files
fix(storage): improve filename generation and conflict handling
Refactor file upload mechanism to generate more readable filenames, prevent special characters, and handle potential filename conflicts by appending a numeric suffix when needed.
1 parent e1857a7 commit 4e87265

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

apps/web/src/functions/supabase-media.ts

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,6 @@ export async function uploadMediaFile(
101101
publicUrl?: string;
102102
error?: string;
103103
}> {
104-
const timestamp = Date.now();
105-
const sanitizedFilename = `${timestamp}-${filename
106-
.replace(/[^a-zA-Z0-9.-]/g, "-")
107-
.toLowerCase()}`;
108-
109104
const allowedExtensions = [
110105
"jpg",
111106
"jpeg",
@@ -118,7 +113,10 @@ export async function uploadMediaFile(
118113
"webm",
119114
"mov",
120115
];
121-
const ext = sanitizedFilename.toLowerCase().split(".").pop();
116+
117+
const parts = filename.split(".");
118+
const ext = parts.pop()?.toLowerCase();
119+
const baseName = parts.join(".").replace(/[^a-zA-Z0-9.-]/g, "-");
122120

123121
if (!ext || !allowedExtensions.includes(ext)) {
124122
return {
@@ -127,7 +125,24 @@ export async function uploadMediaFile(
127125
};
128126
}
129127

130-
const path = folder ? `${folder}/${sanitizedFilename}` : sanitizedFilename;
128+
let finalFilename = `${baseName}.${ext}`;
129+
let path = folder ? `${folder}/${finalFilename}` : finalFilename;
130+
131+
const { data: existingFiles } = await supabase.storage
132+
.from(BUCKET_NAME)
133+
.list(folder || undefined, { limit: 1000 });
134+
135+
if (existingFiles) {
136+
const existingNames = new Set(existingFiles.map((f) => f.name));
137+
let counter = 1;
138+
139+
while (existingNames.has(finalFilename)) {
140+
finalFilename = `${baseName}-${counter}.${ext}`;
141+
counter++;
142+
}
143+
144+
path = folder ? `${folder}/${finalFilename}` : finalFilename;
145+
}
131146

132147
try {
133148
const fileBuffer = Buffer.from(content, "base64");

0 commit comments

Comments
 (0)