Build multipart/form-data POST request in Angular2 and validate Input type File

17,024

Form template

<form id="form" name="file" [formGroup]="FileFormGroup"(submit)="addFrom($event, FileFormGroup)" method="post">  

   <input spellcheck="true" formControlName="Demo" name="Demo" type="text"/>
   <input type="file" accept="image/*" id="file" name="File"/>
   <input formControlName="File" type="hidden"/>

</form>

Ts

   import {FormGroup, FormBuilder, FormControl, Validators} from '@angular/forms';

   import {ValidatorFn} from '@angular/forms/src/directives/validators';

   public FileFormGroup: FormGroup; /* variable */

   constructor(public fb: FormBuilder) {}

   ngOnInit() {
      this.FileFormGroup = this.fb.group({
      Demo: ["", Validators.required],
      File: ["", this.fileExtension({msg: 'Please upload valid Image'})]
     });
   }

   public addFrom(event: Event, form: FormGroup): void {

   if(form.valid && form.dirty) {

   let formTemp: HTMLFormElement <HTMLFormElement>document.querySelector('#form');

   let formData: FormData = new FormData(formTemp);

   let xhr: XMLHttpRequest = this.foo(formData);

    xhr.onreadystatechange = () => {
      if(xhr.readyState === 4) {
        if(xhr.status === 201) {
           console.log("Success");
        } else {
           console.log("Error");
        }
      }
    }
  }}

    // Foo function
     public Foo(formData){
         let url: Foo;
         let xhr: XMLHttpRequest = new XMLHttpRequest();
         xhr.open('POST', url, true);

         // enctype For Multipart Request
          xhr.setRequestHeader("enctype", "multipart/form-data");

          // IE bug fixes to clear cache
          xhr.setRequestHeader("Cache-Control", "no-cache");
          xhr.setRequestHeader("Cache-Control", "no-store");
          xhr.setRequestHeader("Pragma", "no-cache"); 

          xhr.send(formData);
          return xhr;
     }

     /* validation function to check proper file extension */

  public fileExtension(config: any): ValidatorFn {
    return (control: FormControl) => {

      let urlRegEx: RegExp = /\.(jpe?g|png|gif)$/i;

      if(control.value && !control.value.match(urlRegEx)) {
        this.deleteImg = false;
        return {
          invalidUrl: config.msg
        };
      } else {
        return null;
      }
    };
  }
Share:
17,024
Gabe O'Leary
Author by

Gabe O'Leary

For fun I climb mountains and ski, and I'm here in an attempt to improve my web development skills.

Updated on August 11, 2022

Comments

  • Gabe O'Leary
    Gabe O'Leary over 1 year

    I have an image (base64) that I need to send via a POST request (and wait for the response). The POST request needs to be of Content-Type:multipart/form-data. The image needs to be of Content-Type: image/jpg

    The POST request should look like:

    POST https://www.url... HTTP/1.1
    Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
    User-Agent: Fiddler
    Host: www.host.com
    Content-Length: 199640
    
    ---------------------------acebdf13572468
    Content-Disposition: form-data; name="fieldNameHere"; filename="Nikon Digital SLR Camera D3100 14.2MP 2.jpg"
    Content-Type: image/jpeg
    

    With the binary image data as the content body.

    I'm attempting to use the Http Post method of angular 2, but I'm not quite sure about how to generate the request. This is what I have:

    let body = atob(imageData);
    let headers = new Headers({'Content-Type': 'multipart/form-data'});
    let options = new RequestOptions({headers: headers});
    
    this._http.post(url, body, options)
    .map(res=>{
      //do stuff
    });
    

    I can tell that I am missing part of it but I am not sure what I need to do to give the binary image data it's Content-Disposition & Type etc.