Upload a file using Angular

1Upload a file using angular:

Prerequisites:

  1. Html: where we have our input
  2. Component: to handle the input changes
  3. Service: to handle http post request
  4. Module: add the required angular components and services to our module
  5. Enviroment variable: just to make the link global and changeable during building

2Code:

Html:

<input (change)="onFileChange($event)" type="file">
<button (click)="upload()" [disabled]="!file">upload</button>

Component:

import { Component, OnInit } from '@angular/core';
import { FileService } from './file.service';

@Component({
  selector: 'app-yami-code-file',
  templateUrl: './yami-code-file.component.html',
  styleUrls: ['./yami-code-file.component.css']
})
export class YamiCodeFileComponent implements OnInit {

  file: File = null;
  constructor(private fileService: FileService) { }

  ngOnInit() { }

  onFileChange(file) {
    if (file && file.target && file.target.files && file.target.files.item(0)) {
      this.file = file.target.files.item(0)
    } else {
      this.file = null;
    }
  }

  upload() {
    this.fileService.save(this.file).subscribe(file => {
      alert("file uploaded successfully")
    });
  }

}

Service:

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from "../../../../environments/environment";
import { map } from 'rxjs/operators';
import { catchError } from 'rxjs/operators';

@Injectable()
export class FileService {

    private url = environment.url + "upload/";

    constructor(private http: HttpClient) { }

    save(file: File) {
        const formData: FormData = new FormData();
        formData.append('name', file.name);
        formData.append('file', file, file.name);
        return this.postFile(this.url, formData);
    }

    postFile(url: string, formData: FormData) {
        return this.http.post(url, formData)
            .pipe(map((data: any) => { return data; })
                , catchError((error) => {
                    return error;
                }))
            ;
    }
}

Module:

import { YamiCodeFileComponent } from './yami-code-file/yami-code-file.component';
import { FileService } from './yami-code-file/file.service';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
  	//...
    HttpClientModule
  ],
  declarations: [
  	//...
  	YamiCodeFileComponent
  ],
  providers: [
  	//...
  	FileService
  ]
})
export class YamicodeModule { }

Environment:

export const environment = {
  production: false,
  url: "http://localhost:3300/api/"
};