How to upload a file in Angular?

Total
0
Shares
upload-file-angular

Uploading files in Angular requires using FormData() api from Javascript. We need to create a form and append data in its formdata variable. We have tried to make the method more clear by sending the data to file.io API through a POST request.

You may like: Uploading file using ReactJS

Steps to upload files

1. Inside your src/app, open the terminal and generate a new component by using this command:

ng generate component file-uploader

2. Head to app.component.html or your target component and add the generated component tags:

<app-file-uploader></app-file-uploader>

3. Create a service that we will call later inside our file-uploader component, using this command:

ng generate service file-uploader

4. Open file-uploader.component.ts file and edit it using this code:

import { Component, OnInit } from "@angular/core";
import { FileUploaderService } from "../file-uploader.service";

@Component({
  selector: "app-file-uploader",
  templateUrl: "./file-uploader.component.html",
  styleUrls: ["./file-uploader.component.css"]
})

export class FileUploaderComponent implements OnInit {

  shortLink: string = "";
  loading: boolean = false;
  file: File = null;

  //We inject here the service
  constructor(private fileUploaderService: FileUploaderService) {}

  ngOnInit(): void {}

  //Triggered on the selection of file from the user interface
  onChange(event) {
    this.file = event.target.files[0]; //Selects the the content of the file
  }

  onUpload() {

    this.loading = !this.loading; //Displays loading

    console.log(this.file);

    this.fileUploaderService.upload(this.file).subscribe((event: any) => {

      //If the file is uploaded successfully
      if (typeof event === "object") {
        this.shortLink = event.link; //Created link after POST request (file.io)
        this.loading = false; //Hides loading
      }
    });
  }
}

In the code below we are making a call to file-uploader.service.ts after injecting it on the constructor. We subscribe to it and then return the link of the uploaded file, if we had successfully uploaded the file.

5. Do the same thing with file-uploader.service.ts with this code:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable({
    providedIn: "root" //Making the service available to be injected at the application level
})

export class FileUploaderService {

    baseApiUrl = "https://file.io"; //The link to share file to

    constructor(private http: HttpClient) { } //Injecting httpClient to enable us performing any http request

    upload(file): Observable<any> { //We used rxjs library module Observable to be able to subscribe to the service later
        const formData = new FormData(); //Creates an empty form data type variable which will recieve our file later

        formData.append("file", file, file.name); //Adds file data to the file.name from the input with type file in html

        return this.http.post(this.baseApiUrl, formData); //Creates our file in file.io
    }
}

This is the code responsible for uploading our file. Injecting HttpClient library is necessary for making http requests. We had also used RXJS Observable module to be able to subscribe to the flux of data coming from the uploaded file. The last line is responsible for uploading the file in file.io.

6. Now edit file-uploader.component.html file also:

<div class="text-center">
  <input class="form-control" type="file" (change)="onChange($event)" />

  <button (click)="onUpload()" *ngIf="file" class="btn btn-success">
    Upload
  </button>
</div>

<div class="container text-center jumbotron" *ngIf="shortLink">
  <h2>Visit Here</h2>
  <a href="{{shortLink}}">{{shortLink}}</a>
</div>

<div class="container" *ngIf="loading">
  <h3>Loading ...</h3>
</div>

7. Finally we need to import the added components and modules in our app.module.ts:

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FileUploaderComponent } from "./file-uploader/file-uploader.component";
import { AppComponent } from "./app.component";
import { HttpClientModule } from "@angular/common/http";

@NgModule({
    declarations: [AppComponent, FileUploaderComponent],
    imports: [BrowserModule, HttpClientModule],
    providers: [],
    bootstrap: [AppComponent]
})

export class AppModule { }

We have added both the generated FileUploaderComponent in declarations and HttpClientModule under imports otherwise the service won’t work.

Live Demo:

Open Live Demo