Created
September 16, 2022 14:45
-
-
Save reyco1/13329485a4966a3e479382388c5b83b1 to your computer and use it in GitHub Desktop.
Angular Firebase upload service
This file contains 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 { 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