I am new to web API ,Here sending the form data from Angular 4 application to web API.
the form data contains a user registration details as mFormData and the user image as mImage .
I want to store the image in the system folder ex : D:/uplodedImages
and need to store all the user details in database .
I am struggling to do the above things .
service.ts(angular 4)
CreateNewComitteeMember(mFormData, mImage) {
const formData: FormData = new FormData();
formData.append('ImageFile', mImage, mImage.name);
formData.append('mFormData', JSON.stringify(mFormData));
return this.http.post(this.BASE_URL + `/api/CreateNewComitteeMember`, formData)
}
API
[AllowAnonymous]
[HttpPost]
[Route("api/CreateNewComitteeMember")]
public Task<HttpResponseMessage> CreateNewComitteeMember()
{
//How to do the remaining things here.
}
can anyone help me to solve this .
You can simply get the data by accessing the name that you used while appending your data.
But since java object will not be recognized by ASP.NET. You will need to serialize the "mFormData". So, the request will change like this.
formData.append('mFormData', JSON.stringify(mFormData));
Now in you Web API create a model that replicates your "mFormData", lets call it MFormData.
Example,
public class MFormData
{
public string Name {get; set;}
public int Age {get; set;}
public string Xyz {get; set;}
public string ImageUrl {get; set;}
...
}
Now, In your API you can access the data like this.
[AllowAnonymous]
[HttpPost]
[Route("api/CreateNewComitteeMember")]
public Task<HttpResponseMessage> CreateNewComitteeMember()
{
var imageData = HttpContext.Current.Request.Params["mImage"];
var formData = new JavaScriptSerializer()
.Serialize<MFormData>(HttpContext.Current.Request.Params["mFormData"]);
try
{
//Function to save the file and get the URL
formData.ImageUrl = new ApplicationBussinessLayer().SaveFileInDir(imgeData);
//Function to save data in the DB
var saveData = await new AppicationBussinessLayer().SaveUserInfo(formData);
}
catch(Exception ex)
{
return Request.Create(HttpStatusCode.Code, "Some error");
}
return Request.Create(HttpStatusCode.OK, "Data Saved");
}