Ng2 File Upload Remove and Upload Same File

In this lesson, we volition provide a solution to upload multiple files and images to server with angular as a client. We will be creating a sample Angular projection and define a file component and hit REST endpoint to upload files. In that location will exist an option either to select files from local PC or drag and driblet the file from PC to browser and upload them in one shot. For demo purpose, the server will exist a leap boot based server. We will exist using MultipartFile equally RequestParam in spring controller and in the client side we will be using ng2-file-upload and HTML5 FormData.

We will be using Athwart CLI to generate our client projection. While writing this article, the latest version of Angular is 7 and we will make utilise of it merely the implementation volition equally work for Angular 4, Angular 5 and Angular half dozen. We will make utilize of FileSelectDirective and FileDropDirective from ng2-file-upload to achieve this example.

Generating Angular Project

In this article, we won't be discussing the setting upwards Athwart environment. For all those implementations and many more, you can visit my Athwart 7 Grime article. Below are the commands to execute to get started with our Angular projection.

ng new angular-file-upload cd angular-file-upload npm i ng2-file-upload --save ng g component file-upload ng add together @angular/material        

Above commands will generate a new Angular project and adds ng2-file-upload and material designing to it. It also adds our file upload component to it. Now we can import this project into IDE and below will be the terminal projection structure.

angular-file-upload-project-strct

App Module Implementation

We have imported all the required modules hither. All the modules imported hither are the common modules that we import while creating an Athwart project. One affair to discover here is the FileSelectDirective from ng2-file-upload in the declarations. If you do not import this in the declarations section, then in that location will exist a template parse error as Can't demark to 'uploader' since it isn't a known property 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/core';          import          { AppComponent }          from          './app.component';          import          { FileUploadComponent }          from          './file-upload/file-upload.component';          import          {RouterModule}          from          "@angular/router";          import          {FormsModule, ReactiveFormsModule}          from          "@athwart/forms";          import          {FileSelectDirective}          from          "ng2-file-upload";          import          {HttpClientModule}          from          "@angular/mutual/http";          import          {CustomMaterialModule}          from          "./file-upload/fabric.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] })            export class            AppModule { }                  

File Upload Component Implementation

Below is the implementation of our file-upload.component.html. Here, we have a drop-down that provides an option to select the type of epitome to upload and so we accept utilise of ng2FileSelect directive. Hither, we are using restriction of .png file to upload merely you can restrict it for other files besides such every bit .csv etc. The input type that we have defined here supports multiple file upload. Nosotros also have a functionality to drag and driblet 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 name of the file that you take uploaded and also provides an icon to remove the uploaded file. Overall, the implementation is very dynamic and thank you to valor-software for providing this implementation.

<h4>Welcome to {{ title }}!</h4> <mat-card>       <form [formGroup]="uploadForm" (ngSubmit)="uploadSubmit()">         <mat-carte du jour-content>           <mat-grade-field class="form-field">             <mat-label>Select Document Blazon</mat-label>             <mat-select formControlName="type" required>               <mat-option value="Passport">Passport</mat-option>               <mat-option value="Driving_license">Driving License</mat-option>               <mat-pick value="PAN">PAN</mat-option>             </mat-select>           </mat-form-field>           <br>           <input formControlName="certificate" blazon="file" ng2FileSelect have=".png" [uploader]="uploader" multiple/><br/>           <br>           <div form="drop-zone">           <div ng2FileDrop [uploader]="uploader" course="drop-zone">              Drag and drib files to upload           </div>           </div>           <table>             <thead>             <tr>               <thursday width="90%">                 File Name               </th>               <thursday width="10%">                 Remove               </thursday>             </tr>             </thead>             <tbody>             <tr *ngFor="let item of uploader.queue">               <th width="90%">                 {{ particular.file.name}}({{item.file.size/million}} MB)               </thursday>               <th grade="text-middle" width="ten%">                 <mat-icon (click)="particular.remove()">delete</mat-icon>               </th>             </tr>             </tbody>           </table>           <br>           <button mat-raised-button colour="emphasis" [disabled]="!uploadForm.valid" blazon="submit">Upload Data</button>         </mat-card-content>       </course> </mat-card>        

file-upload.component.ts

In the beneath 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 phone call to upload the files.

          import          { Component, OnInit }          from          '@angular/core';          import          {FormBuilder, FormGroup, Validators}          from          "@athwart/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 course          FileUploadComponent          implements          OnInit {    uploadForm: FormGroup;          public          uploader:FileUploader =          new          FileUploader({     isHTML5:          truthful          });   title: string = 'Angular File Upload';          constructor(individual 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){             alarm("Each File should be less than x MB of size.");             return;           }         }          for          (let j = 0; j < this.uploader.queue.length; j++) {           permit data = new FormData();           let fileItem = this.uploader.queue[j]._file;           panel.log(fileItem.name);           information.append('file', fileItem);           data.append('fileSeq', 'seq'+j);           data.suspend( 'dataType', this.uploadForm.controls.type.value);           this.uploadFile(data).subscribe(data => alarm(data.message));         }          this.uploader.clearQueue();   }    uploadFile(data: FormData): Observable            {            return            this.http.post('http://localhost:8080/upload', information);   }    ngOnInit() {              this.uploadForm =              this.fb.group({       document: [null, null],       type:  [null, Validators.compose([Validators.required])]     });   }  }                              

REST API Implementation

Blow is the snippet of the controller class. The method uploadFile() will execute against the API call that we make from the angular client. For an end-to-terminate implementation of this spring boot app, y'all can visit my another article here - Athwart JS File Upload

          @RequestMapping(             value = ("/upload"),             headers =          "content-blazon=multipart/form-data",             method = RequestMethod.Mail service)          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 nosotros created to a higher place where y'all can upload or elevate and drib multiple files.

angular-file-upload-result

Conclusion

In this commodity, we created an Angular 7 customer application that allows multiple files uploading and enables drag and drop feature for file uploading. Yous tin download the source code of this implementation on GItLab here.

lewisportle.blogspot.com

Source: https://www.devglan.com/angular/angular-multiple-file-upload

0 Response to "Ng2 File Upload Remove and Upload Same File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel