File Upload Using Ajax In ASP.NET MVC

Here, we will learn about how can we upload files using Ajax in ASP.NET MVC. We are going to use formData for the file upload. We can also upload multiple images using ajax in ASP.NET MVC.

Let’s start building the application.

Navigate to View -> Shared -> _Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Ajax File Upload", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @RenderSection("scripts", required: false)
</body>
</html>

Open the View -> Home -> Index.cshtml

@{
    ViewBag.Title = "Home Page";
}
<div class="row" style="margin-top:5%">
    <div class="form-group col-md-4">
        <input type="file" class="form-control" id="files" multiple />
    </div>
    <div class="form-group col-md-4">
        <input type="button" id="btnUpload" class="btn btn-info" value="Upload Files" />
    </div>
</div>
<script>
    $(document).on('click', '#btnUpload', function () {
        if (window.FormData !== undefined) {
            var fileUpload = $("#files").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]);
            }
            fileData.append('username', 'Faisal');
            $.ajax({
                url: '/Home/Uploads',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function (result) {
                    alert(result);
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
        } else {
            alert("FormData is not supported in the browser.");
        }
    });
</script>

Finally the code for our controller.

using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace AjaxFileUploadInMVC5.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Uploads()
        {
            if (Request.Files.Count > 0)
            {
                try
                {
                    HttpFileCollectionBase files = Request.Files;
                    for (int i = 0; i < files.Count; i++)
                    {
                        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;
                        }
                        var uploadRootFolderInput = AppDomain.CurrentDomain.BaseDirectory + "\\Uploads";
                        Directory.CreateDirectory(uploadRootFolderInput);
                        var directoryFullPathInput = uploadRootFolderInput;
                        fname = Path.Combine(directoryFullPathInput, 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.");
            }
        }
    }
}

Output:

output

You can download the source code from here

1 Comment

  1. Vüsal

    Hello.thanks for your share. I am also trying to add files. I have 3 fields and for all of them I have to upload another file. Here you have sent more than one file to the same file input. I need to send 3 different files to 3 different inputes and send them to the controls. I also need to save the path of each file in the database according to the id in the controls. My problem is that when I insert, I send the data from the table with js and then send it to the controls with json. Now export these files and how can I send other data at the same time? I will be glad if you help me. Please contact me by e-mail. Thank you.

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories