File Upload on Button Click in Angular 6
In this lesson, nosotros will provide a solution to upload multiple files and images to server with athwart every bit a client. Nosotros volition be creating a sample Angular project and ascertain a file component and hit Residual endpoint to upload files. There will be an option either to select files from local PC or drag and drop the file from PC to browser and upload them in ane shot. For demo purpose, the server will exist a spring boot based server. Nosotros volition be using MultipartFile as RequestParam in spring controller and in the client side we volition be using ng2-file-upload and HTML5 FormData.
We will exist using Angular CLI to generate our client project. While writing this article, the latest version of Angular is vii and nosotros volition brand use of it but the implementation volition equally piece of work for Angular iv, Angular 5 and Angular 6. We will make use of FileSelectDirective and FileDropDirective from ng2-file-upload to attain this instance.
Generating Angular Project
In this commodity, we won't be discussing the setting up Athwart surroundings. For all those implementations and many more than, you lot tin can visit my Angular vii CRUD article. Below are the commands to execute to get started with our Athwart project.
ng new angular-file-upload cd angular-file-upload npm i ng2-file-upload --save ng chiliad component file-upload ng add @angular/cloth
Higher up commands will generate a new Angular projection and adds ng2-file-upload and fabric designing to it. It also adds our file upload component to it. Now nosotros tin import this project into IDE and below volition be the terminal project structure.
App Module Implementation
We take imported all the required modules here. All the modules imported here are the common modules that we import while creating an Angular project. One thing to find hither is the FileSelectDirective
from ng2-file-upload in the declarations. If you practise not import this in the declarations section, then there will be a template parse error equally Can't bind to 'uploader' since it isn't a known property of 'input'.
In the routing configuration, we have divers a default route for FileUploadComponent.
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@athwart/core'; import { AppComponent } from './app.component'; import { FileUploadComponent } from './file-upload/file-upload.component'; import {RouterModule} from "@angular/router"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {FileSelectDirective} from "ng2-file-upload"; import {HttpClientModule} from "@angular/common/http"; import {CustomMaterialModule} from "./file-upload/material.module"; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ declarations: [ AppComponent, FileUploadComponent, FileSelectDirective ], imports: [ BrowserModule, RouterModule, FormsModule, ReactiveFormsModule, HttpClientModule, CustomMaterialModule, RouterModule.forRoot([ {path: '', component: FileUploadComponent} ]), BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
File Upload Component Implementation
Below is the implementation of our file-upload.component.html
. Here, we take a drop-down that provides an option to select the type of image to upload and then we take use of ng2FileSelect directive. Here, nosotros are using restriction of .png file to upload merely yous can restrict it for other files also such equally .csv etc. The input type that we have divers here supports multiple file upload. Nosotros also take a functionality to drag and drop files directly on the browser window from the PC and the file volition be automatically uploaded.
It also has an implementation of table. This table is used show the proper noun of the file that you have uploaded and also provides an icon to remove the uploaded file. Overall, the implementation is very dynamic and cheers to valor-software for providing this implementation.
<h4>Welcome to {{ title }}!</h4> <mat-card> <form [formGroup]="uploadForm" (ngSubmit)="uploadSubmit()"> <mat-card-content> <mat-form-field class="course-field"> <mat-label>Select Document Blazon</mat-label> <mat-select formControlName="type" required> <mat-pick value="Passport">Passport</mat-choice> <mat-option value="Driving_license">Driving License</mat-pick> <mat-selection value="PAN">PAN</mat-option> </mat-select> </mat-class-field> <br> <input formControlName="certificate" type="file" ng2FileSelect accept=".png" [uploader]="uploader" multiple/><br/> <br> <div class="drop-zone"> <div ng2FileDrop [uploader]="uploader" class="drib-zone"> Drag and drop files to upload </div> </div> <tabular array> <thead> <tr> <th width="90%"> File Name </thursday> <th width="10%"> Remove </thursday> </tr> </thead> <tbody> <tr *ngFor="allow item of uploader.queue"> <th width="90%"> {{ item.file.proper name}}({{item.file.size/1000000}} MB) </th> <thursday grade="text-center" width="10%"> <mat-icon (click)="item.remove()">delete</mat-icon> </th> </tr> </tbody> </table> <br> <push mat-raised-push color="accent" [disabled]="!uploadForm.valid" type="submit">Upload Data</button> </mat-card-content> </form> </mat-card>
file-upload.component.ts
In the below implementation, uploadSubmit()
validates the file size first and reads all the files from the queue and adds all the files in the Formdata and makes API call to upload the files.
import { Component, OnInit } from '@angular/core'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {FileUploader} from "ng2-file-upload"; import {Observable} from "rxjs"; import {HttpClient} from "@athwart/common/http"; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html', styleUrls: ['./file-upload.component.css'] }) export grade FileUploadComponent implements OnInit { uploadForm: FormGroup; public uploader:FileUploader = new FileUploader({ isHTML5: true }); title: string = 'Angular File Upload'; constructor(private fb: FormBuilder, private http: HttpClient ) { } uploadSubmit(){ for (let i = 0; i < this.uploader.queue.length; i++) { let fileItem = this.uploader.queue[i]._file; if(fileItem.size > 10000000){ warning("Each File should be less than 10 MB of size."); return; } } for (permit j = 0; j < this.uploader.queue.length; j++) { let data = new FormData(); let fileItem = this.uploader.queue[j]._file; console.log(fileItem.name); data.append('file', fileItem); data.append('fileSeq', 'seq'+j); data.append( 'dataType', this.uploadForm.controls.blazon.value); this.uploadFile(data).subscribe(data => alarm(data.message)); } this.uploader.clearQueue(); } uploadFile(data: FormData): Appreciable{ return this.http.post ('http://localhost:8080/upload', data); } ngOnInit() { this.uploadForm = this.fb.group({ document: [nothing, cipher], type: [null, Validators.compose([Validators.required])] }); } }
REST API Implementation
Blow is the snippet of the controller course. The method uploadFile()
will execute against the API call that we make from the angular client. For an end-to-end implementation of this spring boot app, y'all can visit my another article here - Angular JS File Upload
@RequestMapping( value = ("/upload"), headers = "content-type=multipart/grade-data", method = RequestMethod.POST) public ApiResponse uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("dataType") String dataType) { System.out.println(file.getOriginalFilename()); Organisation.out.println(dataType); return new ApiResponse(HttpStatus.OK, "File uploaded successfully."); }
Testing the Application
Below is the final screenshot of the UI that we created above where you tin upload or drag and drop multiple files.
Decision
In this commodity, we created an Athwart 7 client application that allows multiple files uploading and enables drag and drib feature for file uploading. You tin download the source lawmaking of this implementation on GItLab hither.
Source: https://www.devglan.com/angular/angular-multiple-file-upload