From 32cb19d01f1e521613a2966ea1c58dcf4a6e4c4b Mon Sep 17 00:00:00 2001 From: Austin Chen Date: Sat, 16 Jul 2022 11:37:28 -0700 Subject: [PATCH] Randomize image upload path to avoid collisions --- web/components/editor.tsx | 1 + web/lib/firebase/storage.ts | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/web/components/editor.tsx b/web/components/editor.tsx index bcd49c63..ec4a291c 100644 --- a/web/components/editor.tsx +++ b/web/components/editor.tsx @@ -123,6 +123,7 @@ export function TextEditor(props: { const useUploadMutation = (editor: Editor | null) => useMutation( (files: File[]) => + // TODO: Images should be uploaded under a particular username Promise.all(files.map((file) => uploadImage('default', file))), { onSuccess(urls) { diff --git a/web/lib/firebase/storage.ts b/web/lib/firebase/storage.ts index 2fc2ccc7..4918a99c 100644 --- a/web/lib/firebase/storage.ts +++ b/web/lib/firebase/storage.ts @@ -1,4 +1,5 @@ import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage' +import { nanoid } from 'nanoid' import { storage } from './init' // TODO: compress large images @@ -7,7 +8,10 @@ export const uploadImage = async ( file: File, onProgress?: (progress: number, isRunning: boolean) => void ) => { - const storageRef = ref(storage, `user-images/${username}/${file.name}`) + // Replace filename with a nanoid to avoid collisions + const [, ext] = file.name.split('.') + const filename = `${nanoid(10)}.${ext}` + const storageRef = ref(storage, `user-images/${username}/${filename}`) const uploadTask = uploadBytesResumable(storageRef, file) let resolvePromise: (url: string) => void