×

iFour Logo

How to Implement File Upload in Angular?

Kapil Panchal - February 22, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
How to Implement File Upload in Angular?

File upload functionality is a common requirement professionals expect in any candidate. Angular, being a modern web application development framework helps you with powerful tools to accomplish this task seamlessly. In this comprehensive guide, we will learn practically how to upload a file in Angular, covering various methods and best practices. 

Whether you’re looking to upload files in Angular for the first time or aiming to enhance your existing Angular file upload implementation, this tutorial has you covered. 

Let's move further and walk through a detailed angular file upload example, demonstrating step-by-step how to handle file upload in Angular efficiently. 

Given below are the commonly used elements to perform file upload with Angular.

FormData: Angular File Upload


FormData is an object that you can use for storing key-value pairs. It allows you to construct an object which aligns with an HTML form. This feature allows you to send the data, such as file upload using the XMLHttpRequest interface or Http client libraries.

You can use the following command to create the FormData:

const formdata = new FormData();
				

HttpClientModule: Angular File Upload


HttpClientModule contains an API that you can use to send and fetch the data in your application from the Http servers. You can use the following command to import this module.

Import {HttpClientModule} from ‘@angular/common/http’;
				

Reactive Forms


Reactive forms allow you to use a model-driven approach to manage form inputs. You can use multiple controls in a form group, validate the form values with the help of these forms. You can use the following to import this module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
				

File Upload in Angular


Step 1: Install Angular CLI and create a new project

You can install the angular CLI using this command.

npm install -g @angular/cli
				

You can create a new angular project using the following command.

ng new FileUploadDemo
				

You can use this command to run the project.

ng serve --open
				

Step 2: Add the HttpClientModule

You can import this module in the app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
				

Step 3: Create angular components

You can create components using the following command.

After running this command, angular CLI generates four files of this component and added in the declaration array in the app.module.ts file.

Step 4: Adding angular routing

After creating a component, you can add the routing in the app-routing.module.ts file. First, you need to import this component and then add the routes.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },  
  { path: 'home', component: HomeComponent },  
  { path: 'about', component: AboutComponent },  
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
				

Step 5: Setting up angular material

You can use the following command to add angular material.

In the app.module.ts file, you can add the module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MatToolbarModule  } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
    MatToolbarModule,
    MatCardModule,  
    MatButtonModule,  
    MatProgressBarModule,
    MatIconModule
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
				

Step 6: Create file upload service

You can use the following command to generate a service.

In the UploadService.ts file, write the following code.

import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from  '@angular/common/http';  
import { map } from  'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class UploadService {
  SERVER_URL: string = "https://file.io/";  
  constructor( private httpClient: HttpClient ) { }
  public upload(formData) {
    return this.httpClient.post(this.SERVER_URL, formData, {  
        reportProgress: true,  
        observe: 'events'  
      });  
  }
}

				

Want to Hire Trusted AngularJS Development Company -Enquire Today.

Step 7:After creating the service, you need to define the upload method in the home.component.ts file

import { Component, OnInit, ViewChild, ElementRef  } from '@angular/core';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';  
import { catchError, map } from 'rxjs/operators';  
import { UploadService } from  '../upload.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  @ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files  = [];  
    constructor( private uploadService: UploadService ) { }
  ngOnInit(): void {
  }
  uploadFile(file) {  
    const formData = new FormData();  
    formData.append('file', file.data);  
    file.inProgress = true;  
    this.uploadService.upload(formData).pipe(  
      map(event => {  
        switch (event.type) {  
          case HttpEventType.UploadProgress:  
            file.progress = Math.round(event.loaded * 100 / event.total);  
            break;  
          case HttpEventType.Response:  
            return event;  
        }  
      }),  
      catchError((error: HttpErrorResponse) => {  
        file.inProgress = false;  
        return of(`${file.data.name} upload failed.`);  
      })).subscribe((event: any) => {  
        if (typeof (event) === 'object') {  
          console.log(event.body);  
        }  
      });  
  }
  private uploadFiles() {  
    this.fileUpload.nativeElement.value = '';  
    this.files.forEach(file => {  
      this.uploadFile(file);  
    });  
}

  onClick() {  
    const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => {  
    for ( let index = 0; index < fileUpload.files.length; index++)  
    {  
     const file = fileUpload.files[index];  
     this.files.push({ data: file, inProgress: false, progress: 0});  
    }  
      this.uploadFiles();  
    };  
    fileUpload.click();  
  }
}
				

Next, you need to create an HTML template. Add the following content in the home.component.html file.

  •  
  •  

Next, add the toolbar in the app.component.html file.


ngImageUpload

So that's it, now you are confident enough to implement file uploads in your Angular projects, using features like Angular import file, etc.

 

Looking for assitance? Hire Angular developers from iFour and get your requirements fulfilled.

Conclusion: File Upload in Angular


in this blog, we have seen how to perform file upload in angular. We have started the same by installing angular cli and created an angular application. We installed angular material in the angular application.

How to Implement File Upload in Angular? File upload functionality is a common requirement professionals expect in any candidate. Angular, being a modern web application development framework helps you with powerful tools to accomplish this task seamlessly. In this comprehensive guide, we will learn practically how to upload a file in Angular, covering various methods and best practices.  Whether you’re looking to upload files in Angular for the first time or aiming to enhance your existing Angular file upload implementation, this tutorial has you covered.  Let's move further and walk through a detailed angular file upload example, demonstrating step-by-step how to handle file upload in Angular efficiently.  Given below are the commonly used elements to perform file upload with Angular. FormData: Angular File Upload FormData is an object that you can use for storing key-value pairs. It allows you to construct an object which aligns with an HTML form. This feature allows you to send the data, such as file upload using the XMLHttpRequest interface or Http client libraries. You can use the following command to create the FormData: const formdata = new FormData(); HttpClientModule: Angular File Upload HttpClientModule contains an API that you can use to send and fetch the data in your application from the Http servers. You can use the following command to import this module. Import {HttpClientModule} from ‘@angular/common/http’; Reactive Forms Reactive forms allow you to use a model-driven approach to manage form inputs. You can use multiple controls in a form group, validate the form values with the help of these forms. You can use the following to import this module. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule ], providers: [], bootstrap: [ AppComponent ] }) export class AppModule { } File Upload in Angular Step 1: Install Angular CLI and create a new project You can install the angular CLI using this command. npm install -g @angular/cli You can create a new angular project using the following command. ng new FileUploadDemo You can use this command to run the project. ng serve --open Read More: Implementation Of Ngx Infinite Scroller Using Angular Application Step 2: Add the HttpClientModule You can import this module in the app.module.ts file. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [ AppComponent ] }) export class AppModule { } Step 3: Create angular components You can create components using the following command. After running this command, angular CLI generates four files of this component and added in the declaration array in the app.module.ts file. Step 4: Adding angular routing After creating a component, you can add the routing in the app-routing.module.ts file. First, you need to import this component and then add the routes. import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AboutComponent } from './about/about.component'; import { HomeComponent } from './home/home.component'; const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } Step 5: Setting up angular material You can use the following command to add angular material. In the app.module.ts file, you can add the module. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { MatButtonModule } from '@angular/material/button'; import { MatProgressBarModule } from '@angular/material/progress-bar'; @NgModule({ declarations: [ AppComponent, HomeComponent, AboutComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, BrowserAnimationsModule, MatToolbarModule, MatCardModule, MatButtonModule, MatProgressBarModule, MatIconModule ], providers: [], bootstrap: [ AppComponent ] }) export class AppModule { } Step 6: Create file upload service You can use the following command to generate a service. In the UploadService.ts file, write the following code. import { Injectable } from '@angular/core'; import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from '@angular/common/http'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class UploadService { SERVER_URL: string = "https://file.io/"; constructor( private httpClient: HttpClient ) { } public upload(formData) { return this.httpClient.post(this.SERVER_URL, formData, { reportProgress: true, observe: 'events' }); } } Want to Hire Trusted AngularJS Development Company -Enquire Today. See here Step 7:After creating the service, you need to define the upload method in the home.component.ts file import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { HttpEventType, HttpErrorResponse } from '@angular/common/http'; import { of } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { UploadService } from '../upload.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { @ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files = []; constructor( private uploadService: UploadService ) { } ngOnInit(): void { } uploadFile(file) { const formData = new FormData(); formData.append('file', file.data); file.inProgress = true; this.uploadService.upload(formData).pipe( map(event => { switch (event.type) { case HttpEventType.UploadProgress: file.progress = Math.round(event.loaded * 100 / event.total); break; case HttpEventType.Response: return event; } }), catchError((error: HttpErrorResponse) => { file.inProgress = false; return of(`${file.data.name} upload failed.`); })).subscribe((event: any) => { if (typeof (event) === 'object') { console.log(event.body); } }); } private uploadFiles() { this.fileUpload.nativeElement.value = ''; this.files.forEach(file => { this.uploadFile(file); }); } onClick() { const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => { for ( let index = 0; index < fileUpload.files.length; index++) { const file = fileUpload.files[index]; this.files.push({ data: file, inProgress: false, progress: 0}); } this.uploadFiles(); }; fileUpload.click(); } } Next, you need to create an HTML template. Add the following content in the home.component.html file.     file_upload Upload Next, add the toolbar in the app.component.html file. ngImageUploadHomeAbout So that's it, now you are confident enough to implement file uploads in your Angular projects, using features like Angular import file, etc.   Looking for assitance? Hire Angular developers from iFour and get your requirements fulfilled. Conclusion: File Upload in Angular in this blog, we have seen how to perform file upload in angular. We have started the same by installing angular cli and created an angular application. We installed angular material in the angular application.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Power Apps Solving 13 Legal Challenges
Power Apps Solving 13 Legal Challenges

There is a common misconception that bringing technology into the legal field won't be effective as this profession relies heavily on evidence and facts. However, if you look at it...

How to Automate Power BI Reports Using Power Automate
How to Automate Power BI Reports Using Power Automate

"Does Power Automate work with Power BI?”. If you think the same, you’re at the right place. Manual reporting plays an important role in business decision-making but requires more...

What’s New in .NET 9?
What’s New in .NET 9?

Today, we’re thrilled to present you with the first glimpse of .NET 9 release and let you know what features and updates you can anticipate in this new version. Various professionals believe that it’s the right time to explore and adopt the latest version of .NET for your upcoming projects. It is even recommended for projects built using .NET 6 or .NET 8, due to the framework updates made in this version.