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.
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.
- <div class="float-label-control"> <a class="btn btn-sm btn-primary" href="javascript:;">Upload Contract
- File
- <input class="uploadfile-style" [(ngModel)]="networkContract.FilePath" (change)="fileChange($event)" name="CContractorFPath"
- 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.
- fileChange(event) {
- let fileList: FileList = event.target.files;
- if(fileList.length > 0) {
- let file: File = fileList[0];
- let fileSize:number=fileList[0].size;
- if(fileSize<=10485760)
- {
- let formData:FormData = new FormData();
- formData.append('Document',file);
- formData.append('ClientId', this.clientId);
- formData.append('NetworkOrgID',this.networkContract.NetworkOrgID);
- formData.append('DocumentType','ClientContractDoc');
- if((this.clientId!=undefined && this.clientId>0) &&(this.networkContract.NetworkOrgID!=undefined && this.networkContract.NetworkOrgID>0))
- {
- this._contractInfoTabService.UploadClientContractDoc(formData).subscribe(val => {
- if(val.json().status=='success')
- {
- this.networkContract.FilePath=val.json().data.fileName;
- }
- this.alertService.show(val.json());
- });
- }
- else
- {
- this.alertService.error("Client Name and Contract Org is not selected, please select Client Name and Contract Org first.");
- }
- }
- else
- {
- this.alertService.error("File size is exceeded");
- }
- }
- else
- {
- this.alertService.error("Something went Wrong.");
- }
- }
- formData.append('Document',file);
- formData.append('ClientId', this.clientId);
- formData.append('NetworkOrgID',this.networkContract.NetworkOrgID);
- 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.
- this.alertService.error("File size is exceeded");
- 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.
- UploadClientContractDoc(formData:FormData)
- {
- return this.http.post("ApiUrl",formData)
- .map((response: Response) => {
- return response;
- }).catch(this.handleError);
- }
- .catch(this.handleError); this one for exeception handling
But if you want to use, you need to create an exception method.
- private handleError(error: Response){
- console.error(error);
- return Observable.throw(error.json().error || 'Server error');
- }
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.
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.

Yatendra SrivastavaPosted May 25, 2019, 1:55 PM
Private fileChange(fileInput :any) {alert(fileInput); this.filesToUpload = <Array<File>>fileInput.target.files; const formData: any = new FormData(); const files: Array<File> = this.filesToUpload; console.log(files); for(let i =0; i < files.length; i++){ formData.append("uploads[]",files[i],files[i]['name']); } alert(JSON.stringify(formData)); this.authenticationService.upload_data(formData).subscribe( data => { setTimeout(() => { // alert('done!'); this.alertService.success('Data added successfully'); this.loading = false; }, 1000); }, error => { this.alertService.error(error); this.loading = true; }); }
Sinuhé GómezPosted Oct 25, 2017, 6:10 PM
Hi. Excuse me, do you know if is kinda normal this? When I do console.dir(formData) , it appears that doesn't have any element, but if I do: console.dir(formData.get("name_of_element")) it actually prints out the element. Do you know if this is normal? Do you know where can I find the FormData documentation or something? Thank you so Much! :D
Muhammad SaleemPosted Oct 4, 2017, 7:49 AM
How to catch or receive formData in web api project. my web api code is HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName); //postedFile.SaveAs(filePath); } } actually i am uploading a simple image but its not working and not giving any error. I am checking using debugger. debugger is working but httpRequest.Files.Count is always zero. Plz let me know if you have any solution.
Chandresh MakwanaPosted Oct 2, 2017, 4:18 PM
Hi Bikesh, I tried the same using Angular 4, as I am working on a project which uses that. However, the philosophy is little changed. I always encounter the error - 'Incorrect Content-Type: application/json'. Actually, I am uploading a single image file and a JSON serialized object associated with that. I practically observed that setting the content type to multi-part form data makes no sense at all. Without that, the browser always ends up initializing the header with application/json. This ultimately causes the error that I am facing. Please let me know if you have any solution on that.