I am using ASP.NET MVC 5 for the back-end and Angular + Typescript for the front-end of a web application.
I am trying to upload a file to the server, but for some reason the controller is not getting the file as parameter (the parameter in the controller is null).
I'm sharing below code.
Thanks in advance!
HTML:
<input id="filePath" name="filePath" type="file" accept="image/*" />
<a id="uploadImage" ng-click="ctrl.uploadFile()">Upload</a>
Typescript:
// controller class:
uploadFile(): void {
var filePathInput: any = $("#filePath");
if (filePathInput[0].files) {
var file: any = filePathInput[0].files[0];
var resource: any = this.service.uploadFile();
resource.save(file, (result: any) => {
if (!result || !result.success) {
alert("error");
} else {
alert("ok");
}
});
}
}
// service class:
uploadFile(): ng.resource.IResourceClass<IMyResource> {
return this.$resource("/MyController/UploadImage", null, { method: "POST" });
}
Backend Controller:
[HttpPost]
public JsonResult UploadImage([FromBody]HttpPostedFileBase file)
{
if (file == null || file.ContentLength == 0)
{
return NullParameterResponse();
}
else
{
file.SaveAs("/img/" + Path.GetFileName(file.FileName));
return SuccessResponse();
}
}