Problem :
API controller cannot access HTTP request data which are included FormData object in HTTP request
I need to pass file object data appended in FormData Object in http Post request to asp.net api controller and front-end is angularjs.i can not retrieve http request data from api controller.my code is below. please look into this, it would be great :)
when i pass,
Content-type : undefined
the error says 415 Unsupported Media Type
if Content-type: multipart/form-data
then cannot access data from API controller.
Front-end
$scope.submit = function (files) {
var formData = new FormData();
var getFormData = function(appendFiles){
if (appendFiles.length) {
angular.forEach(appendFiles,function(file){
if(!file.uploaded){
formData.append("imgFiles",file);
file.uploaded = true;
}
});
} else {
formData.append('imgFiles', files);
}
console.log(formData.values());
return formData;
}
$http({
url : "URL",
method: "POST",
data: getFormData(files),
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity,
})
.then(
function (resp) {
// alert(JSON.stringify(resp));
console.log(resp)
},
function (resp) {
console.log(resp)
}
);
};
Api controller Method
[HttpPost]
[Route("route")]
public string UploadFiles(List<HttpPostedFileBase> files)
{
var filesToDelete = HttpContext.Current.Request.Files;
//i need to access file here.using param or otherway
return stat;
}
I have solved the problem.i have changed the api controller method as below,
[HttpPost]
[Route("route")]
public async Task<string> UploadFiles()
{
FileUploadService fileService = new FileUploadService();
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
var uploadFolder = "upload folder physical path"
//this method is in below
var provider = GetMultipartProvider(uploadFolder);
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData fileData in provider.FileData)
{
var physicalPath = fileData.LocalFileName;
var fileName = fileData.Headers.ContentDisposition.FileName;
}
return "return value";
}
private MultipartFormDataStreamProvider GetMultipartProvider(string uploadFolder)
{
try
{
var root = HttpContext.Current.Server.MapPath(uploadFolder);
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
return new MultipartFormDataStreamProvider(root);
}
catch (Exception ex)
{
throw ex;
}
}