Introduction
In this article
we will learn about how to post FormData to webapi using
angularjs2.Normally you can post data to webapi in body,but if you want to pass
image and some filed in that case we have to post FormData.
If you are not aware
about how to post multipart form data to webapi go through my article.
I have already explained
How to post Multipart formData in webapi2,you can create webapi to upload
multipart form data.go through and can be test by postman.
In angular2 if have
configured project then all thing will be so easy because its totally component
based.just create component with HTML and use anywhere.
In this example i am
going to create simple application to upload image with field (FormData)
to web api and save in api application folder.
If you are beginner in
angular2 go on my previous article or blog to learn how to setup and how to
start work on angular2.
click on above link and
learn how to create component,module,services and html using angular2 with
typescript using visual studio code.
I think vscode is better
than other to develop angularjs2 applications.
Ok Lets go to learn step
to upload multipart fom data in angular2 to webapi.
If you have already
configured your application and run succesfully,
just add a single line
of html element with input type file.see code
1. <div class="float-label-control">
2. <a class="btn btn-sm btn-primary" href="javascript:;">Upload Contract
3. File
4. <input class="uploadfile-style" [(ngModel)]="networkContract.FilePath" (change)="fileChange($event)" name="CContractorFPath"
5. size="10" type="file"></a></div>
you can see in line of
code fileChange($event) function will call once you select any
file and fire a event to save document.
Now create a function
inside component.ts see code
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 peace
of code i am checking multiple conditions,you can customize or remove 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 line of code
appending value in formdata object with keypair value,you can change key name
and value as per your requirment.
01 line is doc file and
other is normal field.
These fields are coming
from other object,you can change or remove and add if need any extra filed.
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 code i
am also checking size of file,if you need otherwise can remove.
this._contractInfoTabService.UploadClientContractDoc(formData).subscribe(val
=> {
This line of code
calling the service to post formdata object with file and fields.
Now lets go to create
service to hit endpoint.see code
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
codcane i have used..
.catch(this.handleError); this
one for exeception handling
But if you want use you
need to create a exception method other wise remove if you don't need.see
code.
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 so just go and open visual studio and create
webapi.
Now time to create
webapi to take FormData request from angularjs .So I have already written
article on that go through on given below link.
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 learned 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.
You have just read an article that categorized by title AngularJs 2
by title How To Post FormData To WebAPI Using Angular 2. You can bookmark this page with a URL https://bikeshsrivastava.blogspot.com/2017/04/part-46-how-to-post-formdata-to-webapi.html. Thank You!
Author:
Bikesh Srivastava - Tuesday, April 18, 2017
Your website is very unique. Your content is very interesting to read. Thanks for sharing
ReplyDeleteAngular JS Online training
Angular JS training in Hyderabad