Continuing the previous post FileUpload in ASP.Net MVC or you can create new project.
Previously I had shown How to...
MVC:
- Forms Authentication in Asp.Net MVC 5
- Cascading DropDowns in Asp.Net MVC
- AngularJS with Web Api in Asp.net MVC using Token based Authentication
- Ajax helper Based Search in MVC
- Customizing Authorize attribute or Role based Authentication or Authorization in MVC
- Display message when user is not authorized in mvc
- How to use AutoMapper
- select option with multiple values
- CRUD operations using Bootstrap Modal in Asp.Net MVC
- Asynchronous Requests for CRUD operations in Asp.Net MVC
ADD below code in Index.cshtml
<fieldset>
<legend>Upload Multiple Files using Ajax in MVC</legend>
<input type="file" id="FileUpload1" multiple class="btn btn-default" />
<input type="button" id="btnUpload" value="Upload Files" class="btn btn-primary" />
</fieldset>
@section Scripts
{
<script>
$(document).ready(function () {
$('#btnUpload').click(function () {
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
alert(result);
$("#FileUpload1").val("");
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
}
Now in the Home Controller Add the Following ActionResult.
[HttpPost]
public ActionResult UploadFiles()
{
if (Request.Files.Count > 0)
{
try
{
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
No comments:
Post a Comment