I am doing a file upload operation using Angular 2 and HTML file upload control. My code for uploading the file is as follows -
saveDocument(value: any) {
let apiEndPoint: any = 'http://localhost:58736/LandingPage/addUpdateDocument';
let fi = this.FileInput.nativeElement;
if (fi.files && fi.files[0]) {
let fileToUpload = fi.files[0];
let formData: FormData = new FormData();
formData.append('newDocument', fileToUpload, value);
let headers = new Headers();
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this._http.post(`${apiEndPoint}`, formData , options).map(res => res.json()).catch(error => Observable.throw(error)).subscribe(
data => console.log('success'),
error => console.log(error))
}
}
I have a ASP.Net MVC server side method as follows --
[System.Web.Http.HttpPost]
public string addUpdateDocument(HttpPostedFileBase newDocument)
{
string responseMessage = string.Empty;
try
{
if (newDocument.ContentLength > 0)
{
string _FileName = Path.GetFileName(newDocument.FileName);
string _path = Path.Combine(Server.MapPath("~/upload"), _FileName);
newDocument.SaveAs(_path);
}
responseMessage = "Upload Successfull !!";
}
catch(Exception ex)
{
responseMessage = "Upload Successfull !!";
}
return responseMessage;
}
}
This is working fine as long as I am uploading only the file. But I want to send some more information apart from the File. I tried to implement the function as follows --
this._http.post(`${apiEndPoint}`,{'newDocument':formData,'documentMetaData':value} , options).map(res => res.json()).catch(error => Observable.throw(error)).subscribe(
data => console.log('success'),
error => console.log(error))
and then I modified the server side method as follows -
[System.Web.Http.HttpPost]
public string addUpdateDocument(HttpPostedFileBase newDocument, BlankFormsModels documentMetaData)
Where BlankFormsModels is just a class. When I do this, the the Meta data is received in the server side but the file is not received. It comes as null. Please suggest how can POST form data and JSON data in the same request.