Scale Image Pixels on Upload Angular Firebase 2

In this tutorial, nosotros volition learn How to Upload files like Excel, Image or whatsoever document like PDFs to a Spider web Server in Angular awarding using FormGroup class and FormData interface.

This Angular post is compatible with Angular 4 upto latest versions, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11 & Angular 12

We are going to create a simple grade that will accept a file input command to select a file which will be uploaded by clicking on a button.

In Angular, nosotros use the FormData to handle forms that represent the class field controls equally nosotros have in a static HTML page.

How to Upload Files in Athwart using FormData?

Footstep 1) Import required modules

To enable a form to upload files to a remote server using the HTTP mail service 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 '@athwart/forms'; import { HttpClientModule } from '@angular/common/http';  @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     FormsModule,     ReactiveFormsModule,     HttpClientModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }                      
Pace 2) Adding a Form in Component Template

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

            <h3>Upload File</h3>  <course [formGroup]="fileUploadForm" (ngSubmit)="onFormSubmit()">     <div class="row">         <div class="col-sm-12">             <div>                 <h6 class="head-championship margin-top-8"><bridge>UPLOAD</bridge></h6>             </div>         </div>          <div class="col-sm-vi text-center">              <div class="custom-file">                 <input type="file" class="custom-file-input" id="customFile" name="myfile"                     (alter)="onFileSelect($event)" #UploadFileInput>                 <label class="custom-file-label" for="customFile">{{fileInputLabel || 'Cull File'}}</label>             </div>          </div>         <div class="col-sm-half dozen text-centre">             <push button class="btn btn-primary" type="submit">Upload</push>         </div>     </div> </course>          

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

Note: To this form look good, nosotros used bootstrap.css in the alphabetize.html file

Step 3) Update Component class file

Next, nosotros volition add a reference to the input file command using @ViewChild equally ElementRef.

The onFileSelect() method is called when a file is selected. It is besides having a bank check for Excel file, merely yous can add your own file blazon checks for Docs, PDFs or Images or just remove this check for all file types.

You can become a listing of file MIMEs hither

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

The last component form file will expect like this:

              import { Component, OnInit, ViewChild, ElementRef } from '@angular/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 form UploadfileComponent implements OnInit {    @ViewChild('UploadFileInput', { static: false }) uploadFileInput: ElementRef;   fileUploadForm: FormGroup;   fileInputLabel: cord;    constructor(     private http: HttpClient,     private formBuilder: FormBuilder   ) { }    ngOnInit(): void {     this.fileUploadForm = this.formBuilder.grouping({       myfile: ['']     });   }    onFileSelect(consequence) {     let af = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel']     if (issue.target.files.length > 0) {       const file = effect.target.files[0];       // console.log(file);        if (!_.includes(af, file.type)) {         alert('Only EXCEL Docs Allowed!');       } else {         this.fileInputLabel = file.name;         this.fileUploadForm.become('myfile').setValue(file);       }     }   }     onFormSubmit() {      if (!this.fileUploadForm.get('myfile').value) {       alert('Please make full valid details!');       render false;     }      const formData = new FormData();     formData.append('formFile', this.fileUploadForm.get('myfile').value);     formData.append('agentId', '007');       this.http       .post<any>('http://world wide web.example.com/api/upload', formData).subscribe(response => {         panel.log(response);         if (response.statusCode === 200) {           // Reset the file input           this.uploadFileInput.nativeElement.value = "";           this.fileInputLabel = undefined;         }       }, mistake => {         panel.log(error);       });   }  }                          

Note: In the onFileSelect method we used _.includes lodash method to observe a match in the assortment. The lodash is added by default in the latest Angular versions.

That'due south information technology using above form you can upload whatsoever type of file using FormData class in Athwart application.

gadsonhavize.blogspot.com

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

0 Response to "Scale Image Pixels on Upload Angular Firebase 2"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel