Randomize image upload path to avoid collisions

This commit is contained in:
Austin Chen 2022-07-16 11:37:28 -07:00
parent 1bc49dc0a2
commit 32cb19d01f
2 changed files with 6 additions and 1 deletions

View File

@ -123,6 +123,7 @@ export function TextEditor(props: {
const useUploadMutation = (editor: Editor | null) => const useUploadMutation = (editor: Editor | null) =>
useMutation( useMutation(
(files: File[]) => (files: File[]) =>
// TODO: Images should be uploaded under a particular username
Promise.all(files.map((file) => uploadImage('default', file))), Promise.all(files.map((file) => uploadImage('default', file))),
{ {
onSuccess(urls) { onSuccess(urls) {

View File

@ -1,4 +1,5 @@
import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage' import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage'
import { nanoid } from 'nanoid'
import { storage } from './init' import { storage } from './init'
// TODO: compress large images // TODO: compress large images
@ -7,7 +8,10 @@ export const uploadImage = async (
file: File, file: File,
onProgress?: (progress: number, isRunning: boolean) => void 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) const uploadTask = uploadBytesResumable(storageRef, file)
let resolvePromise: (url: string) => void let resolvePromise: (url: string) => void