How to implement File Upload in Angular? (2024)

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

How to implement File Upload in Angular? (2024)
Top Articles
KPMG’s Singapore Budget 2022 Proposal Highlights ESG, Global Tax And Enterprise Support Measures To Build Lasting Companies On A Fragile Planet - Techspace Africa
Best Socially Conscious Investment Advisors
Craigslist San Francisco Bay
Nullreferenceexception 7 Days To Die
Po Box 7250 Sioux Falls Sd
Shoe Game Lit Svg
The Atlanta Constitution from Atlanta, Georgia
Booknet.com Contract Marriage 2
Ixl Elmoreco.com
2024 Fantasy Baseball: Week 10 trade values chart and rest-of-season rankings for H2H and Rotisserie leagues
Weapons Storehouse Nyt Crossword
Best Private Elementary Schools In Virginia
Rainfall Map Oklahoma
Beau John Maloney Houston Tx
Mini Handy 2024: Die besten Mini Smartphones | Purdroid.de
Haunted Mansion Showtimes Near Millstone 14
Xomissmandi
Toy Story 3 Animation Screencaps
3S Bivy Cover 2D Gen
Alfie Liebel
Ally Joann
Moving Sales Craigslist
UPS Store #5038, The
Poe Str Stacking
Home
Galaxy Fold 4 im Test: Kauftipp trotz Nachfolger?
Idle Skilling Ascension
Walgreens On Bingle And Long Point
Bolly2Tolly Maari 2
Pacman Video Guatemala
Harrison 911 Cad Log
Jailfunds Send Message
101 Lewman Way Jeffersonville In
100 Million Naira In Dollars
The Rise of "t33n leaks": Understanding the Impact and Implications - The Digital Weekly
Bursar.okstate.edu
Haunted Mansion Showtimes Near Cinemark Tinseltown Usa And Imax
Envy Nails Snoqualmie
Amici Pizza Los Alamitos
Craigslist Car For Sale By Owner
School Tool / School Tool Parent Portal
19 Best Seafood Restaurants in San Antonio - The Texas Tasty
Uvalde Topic
Let's co-sleep on it: How I became the mom I swore I'd never be
Carteret County Busted Paper
All Weapon Perks and Status Effects - Conan Exiles | Game...
Senior Houses For Sale Near Me
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Rheumatoid Arthritis Statpearls
Shannon Sharpe Pointing Gif
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 6047

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.