Saturday, March 4, 2017

FileUpload in ASP.Net MVC using Ajax

In this post I will show you how to upload multiple files using Ajax in MVC.
Continuing the previous post FileUpload in ASP.Net MVC or you can create new project.
Previously I had shown How to...
MVC:
Output:


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