Upload File From Ng2 File Upload to Spring
In this lesson, we will provide a solution to upload multiple files and images to server with angular as a client. We volition be creating a sample Angular project and define a file component and hit REST endpoint to upload files. At that place volition be an option either to select files from local PC or drag and drop the file from PC to browser and upload them in one shot. For demo purpose, the server volition be a jump boot based server. We will be using MultipartFile every bit RequestParam in spring controller and in the client side we will be using ng2-file-upload and HTML5 FormData.
We volition exist using Athwart CLI to generate our client project. While writing this article, the latest version of Angular is seven and we will make use of information technology but the implementation will equally work for Angular 4, Athwart five and Angular six. We will make utilise of FileSelectDirective and FileDropDirective from ng2-file-upload to achieve this example.
Generating Angular Project
In this article, we won't exist discussing the setting upwards Angular environment. For all those implementations and many more, y'all tin can visit my Angular 7 Grime article. Below are the commands to execute to go started with our Angular project.
ng new angular-file-upload cd athwart-file-upload npm i ng2-file-upload --save ng g component file-upload ng add @angular/fabric
Above commands will generate a new Angular project and adds ng2-file-upload and material designing to it. Information technology also adds our file upload component to it. At present nosotros tin can import this project into IDE and below will be the final projection construction.
App Module Implementation
We accept imported all the required modules here. All the modules imported here are the mutual modules that we import while creating an Angular project. 1 thing to notice here is the FileSelectDirective from ng2-file-upload in the declarations. If y'all practise non import this in the declarations section, then in that location volition be a template parse error every bit Tin't bind to 'uploader' since information technology isn't a known belongings of 'input'.
In the routing configuration, we have defined a default route for FileUploadComponent.
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/cadre'; 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/textile.module"; import { BrowserAnimationsModule } from '@athwart/platform-browser/animations'; @NgModule({ declarations: [ AppComponent, FileUploadComponent, FileSelectDirective ], imports: [ BrowserModule, RouterModule, FormsModule, ReactiveFormsModule, HttpClientModule, CustomMaterialModule, RouterModule.forRoot([ {path: '', component: FileUploadComponent} ]), BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent] }) consign grade AppModule { }
File Upload Component Implementation
Below is the implementation of our file-upload.component.html. Here, we have a driblet-downwards that provides an pick to select the blazon of image to upload and then we have use of ng2FileSelect directive. Hither, nosotros are using restriction of .png file to upload but y'all tin restrict it for other files too such every bit .csv etc. The input type that we have defined here supports multiple file upload. We too have a functionality to drag and drop files directly on the browser window from the PC and the file will exist automatically uploaded.
It too has an implementation of tabular array. This table is used bear witness the name of the file that you take uploaded and besides provides an icon to remove the uploaded file. Overall, the implementation is very dynamic and thanks to valor-software for providing this implementation.
<h4>Welcome to {{ championship }}!</h4> <mat-card> <course [formGroup]="uploadForm" (ngSubmit)="uploadSubmit()"> <mat-card-content> <mat-form-field course="grade-field"> <mat-characterization>Select Document Blazon</mat-characterization> <mat-select formControlName="type" required> <mat-pick value="Passport">Passport</mat-selection> <mat-pick value="Driving_license">Driving License</mat-option> <mat-option value="PAN">PAN</mat-option> </mat-select> </mat-form-field> <br> <input formControlName="document" type="file" ng2FileSelect accept=".png" [uploader]="uploader" multiple/><br/> <br> <div class="driblet-zone"> <div ng2FileDrop [uploader]="uploader" class="drop-zone"> Drag and driblet files to upload </div> </div> <table> <thead> <tr> <thursday width="90%"> File Name </th> <thursday width="10%"> Remove </th> </tr> </thead> <tbody> <tr *ngFor="let item of uploader.queue"> <th width="90%"> {{ item.file.name}}({{item.file.size/million}} MB) </th> <th grade="text-heart" width="10%"> <mat-icon (click)="detail.remove()">delete</mat-icon> </th> </tr> </tbody> </table> <br> <button mat-raised-push colour="accent" [disabled]="!uploadForm.valid" type="submit">Upload Data</button> </mat-bill of fare-content> </form> </mat-card> file-upload.component.ts
In the below implementation, uploadSubmit() validates the file size kickoff 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/cadre'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {FileUploader} from "ng2-file-upload"; import {Appreciable} from "rxjs"; import {HttpClient} from "@athwart/common/http"; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html', styleUrls: ['./file-upload.component.css'] }) export class FileUploadComponent implements OnInit { uploadForm: FormGroup; public uploader:FileUploader = new FileUploader({ isHTML5: true }); championship: cord = 'Athwart File Upload'; constructor(private fb: FormBuilder, private http: HttpClient ) { } uploadSubmit(){ for (let i = 0; i < this.uploader.queue.length; i++) { permit fileItem = this.uploader.queue[i]._file; if(fileItem.size > 10000000){ warning("Each File should exist less than ten MB of size."); return; } } for (let j = 0; j < this.uploader.queue.length; j++) { allow information = new FormData(); let fileItem = this.uploader.queue[j]._file; console.log(fileItem.name); data.suspend('file', fileItem); information.append('fileSeq', 'seq'+j); data.append( 'dataType', this.uploadForm.controls.type.value); this.uploadFile(information).subscribe(data => alert(information.bulletin)); } this.uploader.clearQueue(); } uploadFile(information: FormData): Observable{ return this.http.post ('http://localhost:8080/upload', data); } ngOnInit() { this.uploadForm = this.fb.grouping({ document: [null, null], type: [goose egg, Validators.compose([Validators.required])] }); } }
REST API Implementation
Blow is the snippet of the controller course. The method uploadFile() will execute confronting the API telephone call that we brand from the angular client. For an stop-to-end implementation of this spring boot app, you tin can visit my another article hither - Angular JS File Upload
@RequestMapping( value = ("/upload"), headers = "content-type=multipart/form-data", method = RequestMethod.POST) public ApiResponse uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("dataType") String dataType) { Organisation.out.println(file.getOriginalFilename()); System.out.println(dataType); return new ApiResponse(HttpStatus.OK, "File uploaded successfully."); }
Testing the Application
Beneath is the terminal screenshot of the UI that we created above where y'all can upload or drag and drop multiple files.
Conclusion
In this article, we created an Athwart 7 client application that allows multiple files uploading and enables drag and drop feature for file uploading. You can download the source code of this implementation on GItLab here.
Source: https://www.devglan.com/angular/angular-multiple-file-upload
0 Response to "Upload File From Ng2 File Upload to Spring"
Postar um comentário