UPLOADING AN IMAGE TO FIREBASE CLOUD STORAGE WITH ANGULAR
Published: 2020-02-17 21:35:59

In this tutorial, we are going to learn how to upload an image to Firebase Cloud Storage from an Angular Project. We’ll be using AngularFire library for setting up Firebase in the Angular web application.

Firebase is Google's mobile platform that helps you quickly develop high-quality apps and grow your business.

### Table of Contents
1. Prerequisites
2. Setup Angular Project using Angular CLI
3. Setup Firebase (AngularFire library) in Angular
4. Create a firebase project
5. Project
6. Conclusion

### Prerequisite
To work with this demo, you must have Node.js and Angular CLI installed on your system. If you are a beginner then you should check out this link to Download node.js

Enter the command below in your terminal to install the latest version of Angular CLI:

```bash
npm install @angular/cli -g
```

### Create an angular project
To create a new Angular project, run the following:

```bash
ng new cloudstorage
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS
cd cloudstorage
```
This command does the initial setup for our Angular projects and installs the dependencies specified in package.json. Then we switch to the new project directory.

### Setup AngularFire library in your Angular Project
The next step is to install AngularFire library. On your terminal, run this:

```bash
npm install firebase @angular/fire --save
```

Once you are done with setting up the angular project next step is to create a connection between firebase and your angular project.

###  Create a firebase project
Go to [Firebase console](https://console.firebase.google.com/) and create a new project.

![image](https://res.cloudinary.com/practicaldev/image/fetch/s--irmCoQop--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/i/bdeq2jpv1g8791xs33nw.png)

Afterward, enter your project name, accept the terms and condition and click on create a project button.

![image](https://res.cloudinary.com/practicaldev/image/fetch/s--XwIr0enF--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/i/8nwkpz28yjqd85g087y9.png)

Once your project is set up, click on your project and you’ll see your admin dashboard. Click project overview > project settings > add app. click on add app button, and fill in the necessary details and your firebase credentials will appear.

![image](https://res.cloudinary.com/practicaldev/image/fetch/s--6hU7pjtG--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/i/ppfh28n2wjai7gbu9amq.jpg)


Copy your firebase credentials and open your Angular app. Go to **src/environments/enviorment.ts and enviorment.prod.ts** files in your project folder. Then add your firebase configuration details in both the environment files as shown below.

![image](https://www.positronx.io/wp-content/uploads/2018/09/ang-setting.jpg)

Now, import **AngularFireModule** and **environment.ts** in **app.module.ts** file, then declare AngularFireModule into the import array.

You can optionally use your FirebaseApp name with the itializeApp method

```javascript
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { AngularFireModule } from "@angular/fire";
import { environment } from "../environments/environment";
import {
  AngularFireStorageModule,
  AngularFireStorageReference,
  AngularFireUploadTask,
  StorageBucket
} from "@angular/fire/storage";
import { ApiService } from "./services/api.service";

@NgModule({
  declarations: [AppComponent],
  imports: [
    HttpClientModule,
    BrowserModule,
    AppRoutingModule,
    AngularFireStorageModule,
    AngularFireModule.initializeApp(environment.firebaseConfig, "cloud")
  ],
  providers: [
    ApiService,
    { provide: StorageBucket, useValue: "your" }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
```

Now you are all set to use Firebase storage in your Angular App. Let’s move over to our app.component.html. You can delete all the default code init except this code below.

```html
<router-outlet> </router-outlet>
```

then we can now add our input tag which we will use to select our file from our computer and bind it to a function whenever the file selected changes.

```html
<div class="form-group col-12">
 <input type="file"
 id="file"
 #userPhoto
 (change)="onFileSelected($event)"
 name="image"
 autocomplete="off"
 />
</div>
<router-outlet> </router-outlet>
```

We now write the javascript code that will run the upload method in our app.component.ts
 **app.component.ts**

```javascript
import { Component } from "@angular/core";
import { ApiService } from "./services/api.service";
import { AngularFireStorage } from "@angular/fire/storage";
import { map, finalize } from "rxjs/operators";
import { Observable } from "rxjs";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  title = "cloudsSorage";
  selectedFile: File = null;
  fb;
  downloadURL: Observable<string>;
  constructor(private Api: ApiService, private storage: AngularFireStorage) {}
  ngOnInit() {}
  onFileSelected(event) {
    var n = Date.now();
    const file = event.target.files[0];
    const filePath = `RoomsImages/${n}`;
    const fileRef = this.storage.ref(filePath);
    const task = this.storage.upload(`RoomsImages/${n}`, file);
    task
      .snapshotChanges()
      .pipe(
        finalize(() => {
          this.downloadURL = fileRef.getDownloadURL();
          this.downloadURL.subscribe(url => {
            if (url) {
              this.fb = url;
            }
            console.log(this.fb);
          });
        })
      )
      .subscribe(url => {
        if (url) {
          console.log(url);
        }
      });
  }
}

```
To upload a file to cloud storage you first create a reference to the full path of the file, including the file name.

In the above code, we start by declaring a variable to hold the **filePath** where the images will be stored in the cloud and we declared another variable **fileRef** which points to the path where the image is stored and the **task** variable holds different properties of the upload state like the total bytes of the file to upload, how many bytes have been uploaded and more. We can use these to upload a progress bar to notify the user of how much of the file has been uploaded. After that, we get the image URL by calling **.getDownloadURL()** and we can now pass it to our API endpoint.

If everything was done correctly, our app will be ready to make our first upload. We can test it to know if our code is working by running:

```bash
ng serve -o
```

If our app is done serving you can now open the app in your browser using this URL: Localhost:4200 after that open your dev tool to see how the upload run and after running.

![image](https://res.cloudinary.com/practicaldev/image/fetch/s--GM_cM7Wh--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/i/oxa8440eqroa0v0g1etf.png)

If you don't see that in your console, you might have missed a step. Look through the steps again to see what you are missing out. But if you see that it means your code is working and if you go to your firebase storage, you will see the image you uploaded.

![image](https://res.cloudinary.com/practicaldev/image/fetch/s--4VZCRk7S--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/i/fmzb2zrg8x32r55jkofo.png)

### Project Files
Click on the below button to get the code files from Git repo.
[github](https://github.com/FayVik/cloudstorage)

### Conclusion
In this tutorial, we talked about Google Firebase Cloud Storage and its powerful features. We have learned how to create a firebase project. How to setup firebase services in your Angular project, and how to upload an image to Firebase Cloud Storage. I hope you love this tutorial. If you find this article useful share it to reach others.