2022-07-14 16:44:52 +00:00
|
|
|
import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage'
|
2022-07-25 19:51:51 +00:00
|
|
|
import imageCompression from 'browser-image-compression'
|
2022-07-16 18:37:28 +00:00
|
|
|
import { nanoid } from 'nanoid'
|
2022-07-14 16:44:52 +00:00
|
|
|
import { storage } from './init'
|
2022-02-04 03:04:56 +00:00
|
|
|
|
2022-08-10 18:03:55 +00:00
|
|
|
const ONE_YEAR_SECS = 60 * 60 * 24 * 365
|
|
|
|
|
2022-02-04 03:04:56 +00:00
|
|
|
export const uploadImage = async (
|
|
|
|
username: string,
|
|
|
|
file: File,
|
|
|
|
onProgress?: (progress: number, isRunning: boolean) => void
|
|
|
|
) => {
|
2022-07-16 18:37:28 +00:00
|
|
|
// 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}`)
|
2022-07-25 19:51:51 +00:00
|
|
|
|
|
|
|
if (file.size > 20 * 1024 ** 2) {
|
|
|
|
return Promise.reject('File is over 20 MB.')
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file.size > 1024 ** 2) {
|
|
|
|
file = await imageCompression(file, {
|
|
|
|
maxSizeMB: 1,
|
|
|
|
maxWidthOrHeight: 1920,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-08-10 18:03:55 +00:00
|
|
|
const uploadTask = uploadBytesResumable(storageRef, file, {
|
|
|
|
cacheControl: `public, max-age=${ONE_YEAR_SECS}`,
|
|
|
|
})
|
2022-02-04 03:04:56 +00:00
|
|
|
|
|
|
|
let resolvePromise: (url: string) => void
|
|
|
|
let rejectPromise: (reason?: any) => void
|
|
|
|
|
|
|
|
const promise = new Promise<string>((resolve, reject) => {
|
|
|
|
resolvePromise = resolve
|
|
|
|
rejectPromise = reject
|
|
|
|
})
|
|
|
|
|
|
|
|
const unsubscribe = uploadTask.on(
|
|
|
|
'state_changed',
|
|
|
|
(snapshot) => {
|
|
|
|
const progress = snapshot.bytesTransferred / snapshot.totalBytes
|
|
|
|
const isRunning = snapshot.state === 'running'
|
|
|
|
if (onProgress) onProgress(progress, isRunning)
|
|
|
|
},
|
|
|
|
(error) => {
|
|
|
|
// A full list of error codes is available at
|
|
|
|
// https://firebase.google.com/docs/storage/web/handle-errors
|
|
|
|
rejectPromise(error)
|
|
|
|
unsubscribe()
|
|
|
|
},
|
|
|
|
() => {
|
|
|
|
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
|
|
|
|
resolvePromise(downloadURL)
|
|
|
|
})
|
|
|
|
|
|
|
|
unsubscribe()
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
return await promise
|
|
|
|
}
|