Upload and View Files in Firebase Storage using Angular + Firebase Real-time Database

Chinthaka Jayatilake
LinkIT
Published in
6 min readOct 10, 2019
Photo by Mitchell Luo on Unsplash

Firebase is a comprehensive app development platform. It helps us to build apps with more efficiency and quality. It can work as a back-end to our application where we can run our services. It also has Firebase extensions from which you can deploy functionalities to your app using pre-packaged solutions. With all this, Firebase is a stand out among current technologies.

If you are interested in knowing more about Firebase, click the following link to be directed to the Firebase official site where you could enhance your knowledge and awareness regarding it.

It is now time for us to create our Firebase project. In the above link, you will find the option ‘Get Started’. With your google account credentials, you will be able to maintain your Firebase account. So once you get to the Firebase console select the option ‘Add Project’.

Creating a project is a 3 step process. In the 1st step, you need to give a project name. In the 2nd step, it will ask whether we need to add Google analytics to our project. For the moment we can say ‘No’ as this is a sample project. But you can use Google analytics in your future projects. If we do not add Google analytics the 3rd step will be automatically skipped as in the 3rd step we need to give the email account where we need the Google analytics updated. Now we have created our Firebase project.

Screenshot by Author

Now we can select the option ‘Web’ to create a web app. Then we need to give the app a name.. With that, we have created our web app as well.

Screenshot by Author

On your left sidebar, you will find the option ‘Database’. On the initial click, they will ask about the database rules. For the moment we will select the option ‘Test Mode’. This will allow access to public read and write. But after finished developing, we can change the rules. So, for now, it is not something to worry about.

Screenshot by Author

Now from the top, you need to select the option ‘Realtime Database’. Then you can find the tab ‘Rules’. Once you go to that tab your rules must be as below. If not, change it to be as below and publish the changes.

Screenshot by Author

Next is to create our storage. For that select ‘Storage’ from the left sidebar. At the initial selection, you will be asked to get started and in the 1st step you can select ‘Next’. In the 2nd step, you need to set the cloud storage location. With that, you will get your storage. Then go to the tab ‘Rules’ in it and do the below changes. Once it is done publish the changes.

Screenshot by Author
Screenshot by Author
Screenshot by Author

Now you need to move to the project settings and at the bottom of it, you will find the firebaseConfig within script tags. Copy that to a notepad file.

Now it is time to create the Angular project. Please follow the steps in the below link which shows how to install and setup Firebase in your angular project. When following the steps at one stage you will need the code snippet that we have already copied to a notepad file. So use it at the correct step.

Now we could proceed with further implementations. Let us create a basic HTML page to upload and view files. So it is time to move to the app.component.html file.

<h2>File Upload</h2><input type="text" placeholder="Save with Key" name="id" [(ngModel)]="id">
<br><br>
<input type="file" (change)="showPreview($event)">
<button (click)="save()">Save</button>
<h2>File View</h2><input type="text" name="file" [(ngModel)]="file" placeholder="Enter Unique Search Key">
<button (click)="view()">View</button>

We need to create a service to get records from the realtime database and also to add records to it. This could even be done in our app.component.ts file. But that is not the best practice as then we need to write the same code lines over and over again. It is always better to create a service and import it to the component.ts files when required.

import { Injectable, Inject } from '@angular/core';
import { AngularFireList, AngularFireDatabase } from '@angular/fire/database';
@Injectable({
providedIn: 'root'
})
export class FileService { imageDetailList: AngularFireList<any>; fileList: any[]; dataSet: Data = {
id:'',
url:''
};
msg:string = 'error'; constructor(@Inject(AngularFireDatabase) private firebase: AngularFireDatabase) { } getImageDetailList() {
this.imageDetailList = this.firebase.list('imageDetails');
}
insertImageDetails(id,url) { this.dataSet = {
id : id,
url: url
};
this.imageDetailList.push(this.dataSet);
} getImage(value){
this.imageDetailList.snapshotChanges().subscribe(
list => {
this.fileList = list.map(item => { return item.payload.val(); });
this.fileList.forEach(element => {
if(element.id===value)
this.msg = element.url;
});
if(this.msg==='error')
alert('No record found');
else{
window.open(this.msg);
this.msg = 'error';
}
}
);
}
}
export interface Data{
id:string;
url:string;
}

We have reached the last step, which is to implement the app.component.ts file. Here we will be importing the service that we created above and we will be implementing methods to get data from the HTML page and to provide the requested functionalities with the help of the imported service.

import { Component, Inject } from '@angular/core';
import { AngularFireStorage } from '@angular/fire/storage';
import { finalize } from "rxjs/operators";
import { FileService } from './Services/file.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent{ selectedImage: any = null; url:string; id:string; file:string; constructor( @Inject(AngularFireStorage) private storage: AngularFireStorage, @Inject(FileService) private fileService: FileService) { } ngOnInit() {
this.fileService.getImageDetailList();
}
showPreview(event: any) {
this.selectedImage = event.target.files[0];
}
save() { var name = this.selectedImage.name;
const fileRef = this.storage.ref(name);
this.storage.upload(name, this.selectedImage).snapshotChanges().pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe((url) => {
this.url = url;
this.fileService.insertImageDetails(this.id,this.url);
alert('Upload Successful');
})
})
).subscribe();
}
view(){
this.fileService.getImage(this.file);
}
}

It is important to make sure that all the imports which are mentioned at the beginning of the component.ts files are present in the project node modules folder. If not they must be installed as below.

npm install imported_file_name

That is it. The end of the implementation process. Let us try to work with this simple project now. Upload an image and check in the Firebase Realtime database whether a record has been inserted and check the Firebase storage whether the file is added. Next is to enter the ID and try to view the image.

I hope it works for you. This is just a simple project to show how these things work. But with the help of this, you could add Firebase storage in your future projects and implement it further according to your project requirements.

You can view and download the project source code from GitHub.

Cheers!! Have a pleasant day!!

Visit my Official Blog Site to send in your queries directly to me and to read more articles by me…

--

--