I need to upload multiple files in mvc4 using ajax,and I tried to upload files using Ajax in mvc 4 with below code:
$("input[type='file']").on("change", function () {
$("#upload").submit();
});
$("#upload").submit(function () {
var l = window.location;
var base_url = l.protocol + "//" + l.host;
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: base_url + '/ProductSpecific/Upload',
data: formData,
dataType: 'json', encode: true,
async: false,
processData: false,
cache: false,
success: function (data, status, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
I just alert totalFiles inside the script ,it returns the number of files selected for upload.
My controller code is:
public ActionResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++) {
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/img"), fileName);
file.SaveAs(path);
}
return View();
}
Since file upload is styled using and css and view page code is:
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "formbuttons", enctype = "multipart/form-data" }))
{
<span id="upload" class="fileUpload">Upload
<input id ="FileUpload" type="file" class="uploadfile" name="FileUpload" multiple="multiple" />
</span>
}
But always Request.Files.Count is 0 in the controller.