Skip to content

Instantly share code, notes, and snippets.

@mrgarymartin
Last active January 2, 2023 20:06
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 mrgarymartin/f4b72023a15a090530bf65d7614d5ba1 to your computer and use it in GitHub Desktop.
Save mrgarymartin/f4b72023a15a090530bf65d7614d5ba1 to your computer and use it in GitHub Desktop.
File Upload Service
import { FileUpload } from './../../../models/file-upload';
import { FileUploadService } from './../../../services/file-upload.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-company-form',
templateUrl: './company-form.component.html',
styleUrls: ['./company-form.component.scss']
})
export class CompanyFormComponent implements OnInit {
selectedFiles?: FileList;
currentFileUpload?: FileUpload;
percentage = 0;
constructor(private uploadService: FileUploadService) { }
ngOnInit(): void {
}
selectFile(event: any): void {
this.selectedFiles = event.target.files;
}
upload(): void {
if (this.selectedFiles) {
const file: File | null = this.selectedFiles.item(0);
this.selectedFiles = undefined;
if (file) {
this.currentFileUpload = new FileUpload(file);
this.uploadService.pushFileToStorage(this.currentFileUpload);
this.percentage = Math.round(this.uploadService.uploadProgress ? this.uploadService.uploadProgress : 0);
}
}
}
}
import { Firestore } from '@angular/fire/firestore';
import { Injectable } from '@angular/core';
import { ref, Storage, deleteObject, list, uploadBytesResumable, getDownloadURL } from "@angular/fire/storage";
import { Subject } from 'rxjs';
import { FileUpload } from '../models/file-upload';
@Injectable({
providedIn: 'root'
})
export class FileUploadService {
private basePath = '/uploads';
uploadProgress: number = 0;
uploadProgressChange: Subject<number> = new Subject<number>();
constructor(private firebase: Firestore, private storage: Storage) {
this.uploadProgressChange.subscribe((value: number) => {
this.uploadProgress = value;
})
}
pushFileToStorage(fileUpload: FileUpload) {
const filePath = `${this.basePath}/${fileUpload.file.name}`;
const storageRef = ref(this.storage, filePath);
const uploadTask = uploadBytesResumable(storageRef, fileUpload.file);
uploadTask.on('state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
this.updateProgress(progress);
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
console.error(error);
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
// ...
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
// alert(error);
},
() => {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log('File available at', downloadURL);
fileUpload.url = downloadURL;
fileUpload.name = fileUpload.file.name;
this.saveFileData(fileUpload);
});
});
return uploadTask.snapshot.metadata
}
updateProgress(progress: number) {
this.uploadProgressChange.next(progress);
}
private saveFileData(fileUpload: FileUpload): void {
// this.db.list(this.basePath).push(fileUpload);
}
getFiles(numberItems: number) {
const listRef = ref(this.storage, 'files/uid');
return list(listRef, { maxResults: numberItems });
}
deleteFile(fileUpload: FileUpload): void {
this.deleteFileDatabase(fileUpload.key)
.then(() => {
this.deleteFileStorage(fileUpload.name);
})
.catch(error => console.log(error));
}
private deleteFileDatabase(key: string): Promise<void> {
const desertRef = ref(this.storage, key);
return deleteObject(desertRef)
}
private deleteFileStorage(name: string): void {
const storageRef = ref(this.storage, this.basePath);
console.log("implement this if needed.....");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment