Example with ASP.NET MVC
Cshtml
@{ Layout = null; }
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>PostFiles</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
function uploadfile() {
var img1 = $("#file1").val();
var img2 = $("#file2").val();
var img3 = $("#file3").val();
var img4 = $("#file4").val();
var img5 = $("#file5").val();
if (img1 || img2 || img3 || img4 || img5) {
var formData = new FormData();
if (img1) {
var file1 = document.getElementById('file1').files[0];
formData.append(file1.name, file1);
}
if (img2) {
var file2 = document.getElementById('file2').files[0];
formData.append(file2.name, file2);
}
if (img3) {
var file3 = document.getElementById('file3').files[0];
formData.append(file3.name, file3);
}
if (img4) {
var file4 = document.getElementById('file4').files[0];
formData.append(file4.name, file4);
}
if (img5) {
var file5 = document.getElementById('file5').files[0];
formData.append(file5.name, file5);
}
var xhr = new XMLHttpRequest();
var url = "/Estudo/PostFiles";
xhr.open('POST', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//var dados = JSON.parse(xhr.responseText);
}
}
xhr.onload = function (e) {
var response = $.parseJSON(e.target.response);
console.log(response.fileName);
};
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(formData);
$("#file1").val('');
$("#file2").val('');
$("#file3").val('');
$("#file4").val('');
$("#file5").val('');
}
}
</script>
</head>
<body>
<div>
<form action="" method="post" enctype="multipart/form-data" onsubmit="return false;">
<div><input type="file" name="file1" id="file1"></div>
<div><input type="file" name="file2" id="file2"></div>
<div><input type="file" name="file3" id="file3"></div>
<div><input type="file" name="file4" id="file4"></div>
<div><input type="file" name="file5" id="file5"></div>
<button type="button" onclick="uploadfile();">Enviar</button>
</form>
</div>
</body>
</html>
Controler code:
[HttpGet]
public ActionResult PostFiles()
{
return View();
}
[HttpPost]
public JsonResult PostFiles(FormCollection form)
{
HttpFileCollectionBase files = Request.Files;
foreach (String file in files)
{
Request.Files[file].SaveAs(Server.MapPath("~/Arquivos/") + Request.Files[file].FileName);
}
return Json(new { status = true });
}