manifold/web/lib/firebase/storage.ts
mantikoros 03f36cf954
User profile (#44)
* add id, userId to comment

* change user info cloud function and script; move cleanUsername to common

* change user info script

* fix rules

* add fund button: useLocation hook

* profile page

* merge

* profile stuff

* avatar uploading to storage bucket

* changeUserInfo: use transaction

* Styles for profile page

* Edit mode for profile, and more styles

Co-authored-by: James Grugett <jahooma@gmail.com>
2022-02-03 21:04:56 -06:00

50 lines
1.2 KiB
TypeScript

import {
getStorage,
ref,
uploadBytesResumable,
getDownloadURL,
} from 'firebase/storage'
const storage = getStorage()
export const uploadImage = async (
username: string,
file: File,
onProgress?: (progress: number, isRunning: boolean) => void
) => {
const storageRef = ref(storage, `user-images/${username}/${file.name}`)
const uploadTask = uploadBytesResumable(storageRef, file)
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
}