How To Post FormData To WebAPI Using Angular 2

Introduction

In this article, we will learn how to post FormData to WebAPI using Angular 2. Normally, you can post data to WebAPI in the body, but if you want to pass images and some fields, in that case, we have to post FormData.
 
If you are not aware how to post multipart form data to WebAPI, go through my article.
 

In Angular2, if you have configured project, then all the things will be so easy because it's totally component based. Just create a component with HTML and use that anywhere.

In this example, I am going to create simple application to upload image with field (FormData)  to WebAPI and save in API application folder.
 
If you are a beginner in Angular 2, go to my previous article or blog to learn how to setup and how to start work on Angular 2. Just click here... 

Click on the above link and learn how to create component, module, services and HTML using Angular 2 with TypeScript, in Visual Studio code.

I think VS Code is better than other tools to develop Angular 2 applications.
 
Ok, let's learn the steps to upload multipart fomdata in Angular 2 to WebAPI.
 
If you have already configured your application and run it successfully, just add a single line of HTML element with input type file.
  1. <div class="float-label-control"> <a class="btn btn-sm btn-primary" href="javascript:;">Upload Contract    
  2.                                                 File    
  3.                                                 <input class="uploadfile-style" [(ngModel)]="networkContract.FilePath" (change)="fileChange($event)" name="CContractorFPath"                                                     
  4.                                                 size="10" type="file"></a></div>     
You can see in the line of code,  fileChange($event) function will be called once you select any file and fire an event to save document. Now, create a function inside component.ts.
  1. fileChange(event) {   
  2.      let fileList: FileList = event.target.files;  
  3.      if(fileList.length > 0) {  
  4.      let file: File = fileList[0];   
  5.      let fileSize:number=fileList[0].size;  
  6.      if(fileSize<=10485760)  
  7.      {   
  8.      let formData:FormData = new FormData();  
  9.      formData.append('Document',file);  
  10.      formData.append('ClientId'this.clientId);  
  11.      formData.append('NetworkOrgID',this.networkContract.NetworkOrgID);  
  12.      formData.append('DocumentType','ClientContractDoc');  
  13.       if((this.clientId!=undefined && this.clientId>0) &&(this.networkContract.NetworkOrgID!=undefined && this.networkContract.NetworkOrgID>0))  
  14.       {  
  15.      this._contractInfoTabService.UploadClientContractDoc(formData).subscribe(val => {  
  16.       if(val.json().status=='success')  
  17.       {    
  18.         this.networkContract.FilePath=val.json().data.fileName;          
  19.       }  
  20.      this.alertService.show(val.json());  
  21.     });   
  22.      }  
  23.      else  
  24.      {  
  25.      this.alertService.error("Client Name and Contract Org is not selected, please select Client Name and Contract Org first.");  
  26.     }  
  27.      }  
  28.      else  
  29.      {  
  30.        this.alertService.error("File size is exceeded");  
  31.      }       
  32.    }  
  33.    else  
  34.    {  
  35.      this.alertService.error("Something went Wrong.");  
  36.    }  
  37. }  
Inside this piece of code, I am checking multiple conditions. You can customize or remove some as per your requirment.
  1. formData.append('Document',file);  
  2. formData.append('ClientId'this.clientId);  
  3. formData.append('NetworkOrgID',this.networkContract.NetworkOrgID);  
  4. formData.append('DocumentType','ClientContractDoc');   
These lines of code are appending value in formdata object with keypair value. You can change the key name and value as per your requirment. 01 line is doc file and other is normal field. 

These fields are coming from other objects; you can change or remove and add if you need any extra fields.
  1. this.alertService.error("File size is exceeded");  
Alert service is a custom service which is created to display error message in application. You can remove as per your need. In this part of the code, I am also checking the size of the file. If you need, keep it; else you can remove it. 
  1. this._contractInfoTabService.UploadClientContractDoc(formData).subscribe(val => {    
This line of code is calling the service to post formdata object with file and fields. Now, let's go to create service to hit endpoint.
  1. UploadClientContractDoc(formData:FormData)  
  2.   {     
  3.      return this.http.post("ApiUrl",formData)  
  4.             .map((response: Response) => {  
  5.               return response;                 
  6.             }).catch(this.handleError);             
  7.   }  
FormData is predefined class of Angular2. I am passing information with document file via FormData object. You need to create HTTP POST request and pass formdata object as body. Inside this part of code, I have used..
  1. .catch(this.handleError); this one for exeception handling  
But if you want to use, you need to create an exception method.
  1. private handleError(error: Response){  
  2.     console.error(error);  
  3.     return Observable.throw(error.json().error || 'Server error');  
  4.   }  
If you have not created web for that scenario, just go and open Visual Studio and create WebAPI.  Now, it is time to create WebAPI to take FormData request from AngularJS. I have already written article on that.
Get code from my GitHub - https://github.com/Bikeshs/Angular2-Typescript  use "git clone https://github.com/Bikeshs/Angular2-Typescript"  command to clone code from GitHub if you have installed git on your system, otherwise git command will not work.

I hope you have leraned a lot of points - how to upload image with formdata and also check size of image or document, and post FormData to WebAPI using component and services. 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now