Angular File Upload - GeeksforGeeks

29 Jul, 2021
The file upload is an essential component to make a form that store some image kind of data. It helps in applications using image upload or in the file sharing. This file-upload component uses file.io API for uploading file and in return it provides a shareable link. Furthermore, we can send get request to shareable link to get the file but for now, our only focus is on upload section so we only use the post method.
Approach:
Create a new angular app using following command-ng new angular-file-upload Move inside the app by using cd command-cd src/app/Generate new component file-upload-ng g c file-upload/ Open src/app folder and start editing app.component.html file.<app-file-upload></app-file-upload>Create a service for file-upload component via command-ng g s file-upload/Open src/app/file-upload folder and start editing file-upload.component.ts file.import { Component, OnInit } from '@angular/core';import { FileUploadService } from './file-upload.service';  @Component({    selector: 'app-file-upload',    templateUrl: './file-upload.component.html',    styleUrls: ['./file-upload.component.css']})export class FileUploadComponent implements OnInit {      // Variable to store shortLink from api response    shortLink: string = "";    loading: boolean = false; // Flag variable    file: File = null; // Variable to store file      // Inject service     constructor(private fileUploadService: FileUploadService) { }      ngOnInit(): void {    }      // On file Select    onChange(event) {        this.file = event.target.files[0];    }      // OnClick of button Upload    onUpload() {        this.loading = !this.loading;        console.log(this.file);        this.fileUploadService.upload(this.file).subscribe(            (event: any) => {                if (typeof (event) === 'object') {                      // Short link via api response                    this.shortLink = event.link;                      this.loading = false; // Flag variable                 }            }        );    }}Open src/app/file-upload/ and start editing file-upload.service.ts file.import { Injectable } from '@angular/core';import {HttpClient} from '@angular/common/http';import {Observable} from 'rxjs';@Injectable({  providedIn: 'root'})export class FileUploadService {      // API url  baseApiUrl = "https://file.io"      constructor(private http:HttpClient) { }    // Returns an observable  upload(file):Observable<any> {        // Create form data      const formData = new FormData();               // Store form name as "file" with file data      formData.append("file", file, file.name);              // Make http post request over api      // with formData as req      return this.http.post(this.baseApiUrl, formData)  }}Open src/app/file-upload and start editing file-upload.component.html file.<div class="text-center">    <input class="form-control" type="file"             (change)="onChange($event)">      <button (click)="onUpload()"         class="btn btn-success">        Upload    </button></div>  <!-- Shareable short link of  uoloaded file --><div class="container text-center jumbotron"    *ngIf="shortLink">    <h2> Visit Here</h2>    <a href="{{shortLink}}">{{shortLink}}</a></div>  <!--Flag variable is used here--><div class="container" *ngIf="loading">    <h3>Loading ...</h3></div>Open src/app/ and start editing app.module.ts file.import { BrowserModule } from     '@angular/platform-browser';import { NgModule } from '@angular/core';  import { FileUploadComponent } from     './file-upload/file-upload.component';  import { AppComponent } from './app.component';import {HttpClientModule} from     '@angular/common/http';@NgModule({  declarations: [    AppComponent,    FileUploadComponent,  ],  imports: [    BrowserModule,    HttpClientModule  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }Now run this command to serve on localhostng serveOutput:Before file selection:After file selection and clicking on button:After loading is completed:HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.My Personal Notes
arrow_drop_upSave
Create a new angular app using following command-ng new angular-file-upload 
ng new angular-file-upload 
Move inside the app by using cd command-cd src/app/
cd src/app/
Generate new component file-upload-ng g c file-upload/ 
ng g c file-upload/ 
Open src/app folder and start editing app.component.html file.<app-file-upload></app-file-upload>
<app-file-upload></app-file-upload>
Create a service for file-upload component via command-ng g s file-upload/
ng g s file-upload/
Open src/app/file-upload folder and start editing file-upload.component.ts file.import { Component, OnInit } from '@angular/core';import { FileUploadService } from './file-upload.service';  @Component({    selector: 'app-file-upload',    templateUrl: './file-upload.component.html',    styleUrls: ['./file-upload.component.css']})export class FileUploadComponent implements OnInit {      // Variable to store shortLink from api response    shortLink: string = "";    loading: boolean = false; // Flag variable    file: File = null; // Variable to store file      // Inject service     constructor(private fileUploadService: FileUploadService) { }      ngOnInit(): void {    }      // On file Select    onChange(event) {        this.file = event.target.files[0];    }      // OnClick of button Upload    onUpload() {        this.loading = !this.loading;        console.log(this.file);        this.fileUploadService.upload(this.file).subscribe(            (event: any) => {                if (typeof (event) === 'object') {                      // Short link via api response                    this.shortLink = event.link;                      this.loading = false; // Flag variable                 }            }        );    }}
import { Component, OnInit } from '@angular/core';import { FileUploadService } from './file-upload.service';  @Component({    selector: 'app-file-upload',    templateUrl: './file-upload.component.html',    styleUrls: ['./file-upload.component.css']})export class FileUploadComponent implements OnInit {      // Variable to store shortLink from api response    shortLink: string = "";    loading: boolean = false; // Flag variable    file: File = null; // Variable to store file      // Inject service     constructor(private fileUploadService: FileUploadService) { }      ngOnInit(): void {    }      // On file Select    onChange(event) {        this.file = event.target.files[0];    }      // OnClick of button Upload    onUpload() {        this.loading = !this.loading;        console.log(this.file);        this.fileUploadService.upload(this.file).subscribe(            (event: any) => {                if (typeof (event) === 'object') {                      // Short link via api response                    this.shortLink = event.link;                      this.loading = false; // Flag variable                 }            }        );    }}
Open src/app/file-upload/ and start editing file-upload.service.ts file.import { Injectable } from '@angular/core';import {HttpClient} from '@angular/common/http';import {Observable} from 'rxjs';@Injectable({  providedIn: 'root'})export class FileUploadService {      // API url  baseApiUrl = "https://file.io"      constructor(private http:HttpClient) { }    // Returns an observable  upload(file):Observable<any> {        // Create form data      const formData = new FormData();               // Store form name as "file" with file data      formData.append("file", file, file.name);              // Make http post request over api      // with formData as req      return this.http.post(this.baseApiUrl, formData)  }}
import { Injectable } from '@angular/core';import {HttpClient} from '@angular/common/http';import {Observable} from 'rxjs';@Injectable({  providedIn: 'root'})export class FileUploadService {      // API url  baseApiUrl = "https://file.io"      constructor(private http:HttpClient) { }    // Returns an observable  upload(file):Observable<any> {        // Create form data      const formData = new FormData();               // Store form name as "file" with file data      formData.append("file", file, file.name);              // Make http post request over api      // with formData as req      return this.http.post(this.baseApiUrl, formData)  }}
Open src/app/file-upload and start editing file-upload.component.html file.<div class="text-center">    <input class="form-control" type="file"             (change)="onChange($event)">      <button (click)="onUpload()"         class="btn btn-success">        Upload    </button></div>  <!-- Shareable short link of  uoloaded file --><div class="container text-center jumbotron"    *ngIf="shortLink">    <h2> Visit Here</h2>    <a href="{{shortLink}}">{{shortLink}}</a></div>  <!--Flag variable is used here--><div class="container" *ngIf="loading">    <h3>Loading ...</h3></div>
<div class="text-center">    <input class="form-control" type="file"             (change)="onChange($event)">      <button (click)="onUpload()"         class="btn btn-success">        Upload    </button></div>  <!-- Shareable short link of  uoloaded file --><div class="container text-center jumbotron"    *ngIf="shortLink">    <h2> Visit Here</h2>    <a href="{{shortLink}}">{{shortLink}}</a></div>  <!--Flag variable is used here--><div class="container" *ngIf="loading">    <h3>Loading ...</h3></div>
Open src/app/ and start editing app.module.ts file.import { BrowserModule } from     '@angular/platform-browser';import { NgModule } from '@angular/core';  import { FileUploadComponent } from     './file-upload/file-upload.component';  import { AppComponent } from './app.component';import {HttpClientModule} from     '@angular/common/http';@NgModule({  declarations: [    AppComponent,    FileUploadComponent,  ],  imports: [    BrowserModule,    HttpClientModule  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }
import { BrowserModule } from     '@angular/platform-browser';import { NgModule } from '@angular/core';  import { FileUploadComponent } from     './file-upload/file-upload.component';  import { AppComponent } from './app.component';import {HttpClientModule} from     '@angular/common/http';@NgModule({  declarations: [    AppComponent,    FileUploadComponent,  ],  imports: [    BrowserModule,    HttpClientModule  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }
Now run this command to serve on localhostng serveOutput:Before file selection:After file selection and clicking on button:After loading is completed:HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.My Personal Notes
arrow_drop_upSave
ng serve
Output:
Before file selection:
After file selection and clicking on button:
After loading is completed:
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
AngularJS-Misc
HTML-Misc
Picked
AngularJS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Auth Guards in Angular 9/10/11
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)