I am trying to implement the file upload feature in my asp.net mvc web application. But when i try to retrieve the file from the input tag through js, it is always returning null. I am using ajax to send files to the server from my partial view, and the control is successfully getting transferred to the controller but the file is always null. Any help would be appreciated. Thank You.
Partial View
@using (Html.BeginForm("FileUpload",
"Home",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div id="uploadbutton" style="top:50%;position:absolute;height:120px;width:300px;border-width:2px;border-style:dotted;border-radius:20px;display:flex;align-items:center;justify-content:center">
<div style="width:100px;flex-direction:row;display:flex;align-self:center;position:absolute;left:10px">
<label style="margin-right:10px" for="file">Upload:</label>
<input type="file" name="file" id="file" /><br><br>
<br><br>
@ViewBag.Message
</div>
</div>
<button type="submit" id="ProcessButton" style="position:absolute;top:75%;background-color:cornflowerblue;color:brown;border-color:brown;height:40px;width:100px">Process</button>
}
Js code
var fileUpload = $("#file").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '@Url.Action("FileUpload", "Home")',
type: 'POST',
cache: false,
async: true,
data: JSON.stringify(fileData),
contentType: false,
processData: false,
success: function (result) {
alert('cool');
}
});
Controller
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
}
else
{
}
return View();
}