I am uploading file and for that I am using FormData object in jquery ajax and passing it to the ASP.NET MVC WEB API, It's working fine, I am able to get files on server side, but I want to pass some extra details too with same request.
I can add additional data in headers and I am able to fetch on server side from headers but I will use same API's for mobile app too. So if I can pass data as a parameter of function, then it would be nice.
So how to pass additional data in formData object and how to fetch it on server side ?
My code is,
function uploadEvaluationFile() {
var files = $("#file_UploadFile1").get(0).files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file1" + x, files[x]);
}
data.append("UserId", 5);
data.append("ArtCategory", 5);
data.append("Title", "Title1");
data.append("Description", "Desc 1");
$.ajax({
type: "POST",
url: '/Home/saveEvaluationFile',
contentType: false,
processData: false,
data: data,
async: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('identifier', 111);
xhr.setRequestHeader('oldFileName', 222);
},
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (err) {
console.log(err);
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}
}
web api code,
[HttpPost]
public async Task<JsonResult> saveEvaluationFile(EvaluationFileDetails FileData)
{
IEnumerable<string> headerValues = Request.Headers.GetValues("oldFileName");
var oldFileName = headerValues.FirstOrDefault();
IEnumerable<string> headerValues1 = Request.Headers.GetValues("identifier");
var newFileName = headerValues1.FirstOrDefault();
try
{
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
}
}
catch (Exception)
{
return Json("Upload failed");
}
return Json("File uploaded successfully");
}
My class is,
public class EvaluationFileDetails
{
public HttpPostedFileBase file1 { get; set; }
public int UserId { get; set; }
public int ArtCategory { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}