Skip to content

Instantly share code, notes, and snippets.

@benedictchen
Last active April 24, 2024 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benedictchen/3a2fd82ccaf537e6bb1521dc46e4a70d to your computer and use it in GitHub Desktop.
Save benedictchen/3a2fd82ccaf537e6bb1521dc46e4a70d to your computer and use it in GitHub Desktop.
Firebase Cloud Storage Plugin for Uppy (File Uploader Library)
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