Skip to content

Instantly share code, notes, and snippets.

@reyco1
Created September 16, 2022 14:45
Show Gist options
  • Save reyco1/13329485a4966a3e479382388c5b83b1 to your computer and use it in GitHub Desktop.
Save reyco1/13329485a4966a3e479382388c5b83b1 to your computer and use it in GitHub Desktop.
Angular Firebase upload service
import { Injectable } from '@angular/core';
import { getDownloadURL, ref, Storage, StringFormat, uploadBytes, uploadString } from '@angular/fire/storage';
@Injectable({
providedIn: 'root'
})
export class UploadService {
constructor(
private storage: Storage,
) { }
// upload base64 image to the storage
uploadBase64(path: string, base64: string): Promise<string | null> {
const storageRef = ref(this.storage, path);
return uploadString(storageRef, base64, StringFormat.BASE64)
.then(() => getDownloadURL(storageRef));
}
// upload image to the storage
uploadImage(path: string, image: File): Promise<string | null> {
const storageRef = ref(this.storage, path);
return uploadBytes(storageRef, image)
.then(() => getDownloadURL(storageRef));
}
// uploads a json file to the storage
uploadJson(path: string, json: any): Promise<string | null> {
const storageRef = ref(this.storage, path);
const blob = new Blob([JSON.stringify(json)], { type: 'application/json' });
const file = new File([blob], path, { type: 'application/json', lastModified: Date.now() });
return uploadBytes(storageRef, file)
.then(() => getDownloadURL(storageRef));
}
// gets the url of a document in the storage
getUrl(path: string): Promise<string | null> {
return getDownloadURL(ref(this.storage, path))
.catch(() => null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment