Last active
January 10, 2025 22:23
-
-
Save benedictchen/3a2fd82ccaf537e6bb1521dc46e4a70d to your computer and use it in GitHub Desktop.
Firebase Cloud Storage Plugin for Uppy (File Uploader Library)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BasePlugin } from '@uppy/core' | |
import { Uppy, UppyOptions } from '@uppy/core'; | |
import { getAuth } from 'firebase/auth'; | |
import { | |
UploadTaskSnapshot, | |
getDownloadURL, | |
getStorage, | |
uploadBytesResumable, | |
ref, | |
} from 'firebase/storage'; | |
import { v4 as uuid } from 'uuid'; | |
const storage = getStorage(); | |
export default class FirebaseCloudStoragePlugin extends BasePlugin { | |
constructor(uppy: Uppy, opts: UppyOptions) { | |
super(uppy, opts); | |
this.type = 'uploader'; | |
this.id = 'FirebaseCloudStorage'; | |
this.uploadFile = this.uploadFile.bind(this); | |
} | |
uploadFile(fileIds: string[]): Promise<any>{ | |
return Promise.all( | |
fileIds.map((id) => { | |
this.uppy.emit('upload-start', this.uppy.getFiles()); | |
return new Promise<void>((resolve, reject) => { | |
const file = this.uppy.getFile(id); | |
const refId = uuid(); | |
const userId = getAuth().currentUser?.uid; | |
const folder = userId ? `${userId}/` : ''; | |
const storageRef = ref(storage, `${folder}${refId}-[::]-${file.name}`); | |
this.uppy.emit('upload-started', file); | |
const uploadTask = uploadBytesResumable(storageRef, file.data); | |
uploadTask.on( | |
'state_changed', | |
(snapshot: UploadTaskSnapshot) => { | |
const bytesUploaded = snapshot.bytesTransferred; | |
const bytesTotal = snapshot.totalBytes; | |
console.log(`progress happening: ${bytesUploaded}/${bytesTotal}`); | |
this.uppy.emit('upload-progress', file.id, { | |
uploader: this, | |
bytesUploaded, | |
bytesTotal, | |
}); | |
}, | |
(error: Error) => { | |
this.uppy.emit('upload-error', file, error); | |
reject(error); | |
}, | |
async () => { | |
const downloadUrl = await getDownloadURL(uploadTask.snapshot.ref); | |
const file = this.uppy.getFile(id); | |
Object.assign(file, 'downloadUrl', downloadUrl); | |
this.uppy.setFileState(file.id, { status: 'success' }); | |
console.log('Time to emit success', { file, downloadUrl }); | |
this.uppy.emit( | |
'upload-success', | |
file, | |
uploadTask.snapshot, | |
downloadUrl, | |
); | |
resolve(); | |
} | |
); | |
}); | |
}) | |
); | |
} | |
install() { | |
this.uppy.addUploader(this.uploadFile); | |
} | |
uninstall() { | |
this.uppy.removeUploader(this.uploadFile); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment