Upload File to Excel Angular 5 Example

In this tutorial, we volition acquire How to Upload files like Excel, Epitome or whatever document like PDFs to a Spider web Server in Angular awarding using FormGroup grade and FormData interface.

This Angular postal service is compatible with Angular 4 upto latest versions, Angular vii, Athwart 8, Angular 9, Athwart x, Angular 11 & Angular 12

Nosotros are going to create a simple form that will have a file input control to select a file which will be uploaded by clicking on a button.

In Athwart, we use the FormData to handle forms that represent the grade field controls as we have in a static HTML page.

How to Upload Files in Angular using FormData?

Step 1) Import required modules

To enable a grade to upload files to a remote server using the HTTP post method in Angular application, we need to import FormsModule , ReactiveFormsModule and HttpClientModule in the app.module.ts file as shown below:

            // app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core';  import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component';  import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http';  @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     FormsModule,     ReactiveFormsModule,     HttpClientModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }                      
Step ii) Adding a Form in Component Template

Add a simple Form in a component template HTML with [formGroup] and (ngSubmit) event handler. Then add an Input File control and a push to submit the grade as shown below:

            <h3>Upload File</h3>  <form [formGroup]="fileUploadForm" (ngSubmit)="onFormSubmit()">     <div class="row">         <div class="col-sm-12">             <div>                 <h6 class="head-title margin-elevation-viii"><bridge>UPLOAD</bridge></h6>             </div>         </div>          <div class="col-sm-6 text-center">              <div course="custom-file">                 <input type="file" course="custom-file-input" id="customFile" name="myfile"                     (change)="onFileSelect($event)" #UploadFileInput>                 <label course="custom-file-label" for="customFile">{{fileInputLabel || 'Choose File'}}</label>             </div>          </div>         <div course="col-sm-half dozen text-center">             <button grade="btn btn-primary" type="submit">Upload</button>         </div>     </div> </form>          

Above nosotros also added a template reference variable #UploadFileInput to reset the input field after file uploaded successfully.

Annotation: To this class look good, we used bootstrap.css in the index.html file

Step 3) Update Component class file

Next, we will add a reference to the input file command using @ViewChild as ElementRef.

The onFileSelect() method is called when a file is selected. Information technology is also having a check for Excel file, but yous can add your own file blazon checks for Docs, PDFs or Images or simply remove this check for all file types.

You tin can get a listing of file MIMEs here

The onFormSubmit() method is called on course submit, here yous can add together more formData properties if you want using FormData's append method

The final component class file will look like this:

              import { Component, OnInit, ViewChild, ElementRef } from '@athwart/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; import * as _ from 'lodash';  @Component({   selector: 'app-uploadfile',   templateUrl: './uploadfile.component.html',   styleUrls: ['./uploadfile.component.scss'] }) export class UploadfileComponent implements OnInit {    @ViewChild('UploadFileInput', { static: false }) uploadFileInput: ElementRef;   fileUploadForm: FormGroup;   fileInputLabel: string;    constructor(     private http: HttpClient,     private formBuilder: FormBuilder   ) { }    ngOnInit(): void {     this.fileUploadForm = this.formBuilder.group({       myfile: ['']     });   }    onFileSelect(event) {     allow af = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel']     if (event.target.files.length > 0) {       const file = consequence.target.files[0];       // console.log(file);        if (!_.includes(af, file.type)) {         alert('Only EXCEL Docs Allowed!');       } else {         this.fileInputLabel = file.proper name;         this.fileUploadForm.get('myfile').setValue(file);       }     }   }     onFormSubmit() {      if (!this.fileUploadForm.get('myfile').value) {       alert('Please fill up valid details!');       render simulated;     }      const formData = new FormData();     formData.append('formFile', this.fileUploadForm.go('myfile').value);     formData.append('agentId', '007');       this.http       .mail<whatsoever>('http://www.case.com/api/upload', formData).subscribe(response => {         console.log(response);         if (response.statusCode === 200) {           // Reset the file input           this.uploadFileInput.nativeElement.value = "";           this.fileInputLabel = undefined;         }       }, error => {         console.log(error);       });   }  }                          

Note: In the onFileSelect method we used _.includes lodash method to find a match in the array. The lodash is added by default in the latest Athwart versions.

That's it using higher up form you can upload whatsoever type of file using FormData class in Angular application.

armentroutsull1946.blogspot.com

Source: https://www.freakyjolly.com/angular-file-upload-using-formdata/

0 Response to "Upload File to Excel Angular 5 Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel