Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

ASP.NET MVC file upload using Ajax jQuery in MVC

In this tutorial, I am going to explain you how to Upload file in ASP.NET MVC using jQuery Ajax method. I will be using Visual Studio 2013. Below is step by step tutorial.

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Now, a new project will be created as shown below.

Adding Upload Folder

Now add a new folder named UploadFiles to the root directory of the application in which the file will be uploaded or you can use specific location at hard-drive to upload files.

Adding Controller

Next step is to add controller to application. Go to controller folder and add new empty controller named as Home controller. Replace all code with below code. Here first method is Index which returns view that contains markup for file upload. Second index method is post method which is used to save the posted file from view to the hard drive.

Post index method returns result in JSON format with two custom variables success and responseMessage. success variable contains true or false and responseMessage contains different response messgaes.

using System;
usingSystem.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

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

        [HttpPost]
        [ActionName("Index")]
        public JsonResult Index_Post()
        {
            bool flag = true;
            string responseMessage = string.Empty;

            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];

                //add more conditions like file type, file size etc as per your need.
                if (file != null && file.ContentLength > 0 && (Path.GetExtension(file.FileName).ToLower() == ".xlsx" || Path.GetExtension(file.FileName).ToLower() == ".xls"))
                {
                    try
                    {
                        stringfileName = Path.GetFileName(file.FileName);
                        stringfilePath = Path.Combine(Server.MapPath("~/UploadFiles"), fileName);
                        file.SaveAs(filePath);

                        flag = true;
                        responseMessage = "Upload Successful.";
                    }
                    catch (Exception ex)
                    {
                        flag = false;
                        responseMessage = "Upload Failed with error: " + ex.Message;
                    }
                }
                else
                {
                    flag = false;
                    responseMessage = "File is invalid.";
                }
            }
            else
            {
                flag = false;
                responseMessage = "File Upload has no file.";
            }

            return Json(new { success = flag, responseMessage = responseMessage }, JsonRequestBehavior.AllowGet);
        }
    }
}

Adding View

Now, right click on home controller index action method, add new view and name Index. Select Empty template and uncheck Use layout page and click on Add as shown below.

Now go to Views / Home folder, open Index.cshtml file and replace all code with below code.
Here first file is jquery.min.js which is compulsory file and other two bootstrap files are used for styling the View.

Index.cshtml Code:
script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">script>
script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">script>
link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

script>
    $(function () {
        $('#btnUpload').click(function () {

            if ($("#fileID").val() == '') {
                alert('Please select a file.');
                return false;
            }

            var formData = new FormData();
            var file = document.getElementById("fileID").files[0];
            formData.append("MyFile", file);

            $.ajax({
                type: "POST",
                url: '/Home/Index/',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                cache: false,
                success: function (response) {
                    var myhtml = '';
                    if (response.success) {

                        myhtml = '
' + response.responseMessage + '
'
;
                    }
                    else {
                        myhtml = '
' + response.responseMessage + '
'
;
                    }
                    $("#myAlert").html(myhtml);
                    $("#myAlert").fadeIn(500).delay(3000).fadeOut(500);
                },
                error: function (error) {
                    $("#myAlert").html('
' + error + '
'
);
                }
            });
        });
    });
script>

table class="table text-centered" style=" border-radius: 5px; width: 30%; margin: 0px auto; float: none;">
    thead>
        tr>
            th colspan="2">File Upload Using Ajax jQuery in MVCth>
        tr>
    thead>
    tbody>
        tr>
            td>
                @Html.TextBox("fileID", "", new { type = "file" })
                @**@
            td>
            td>
                input type="submit" id="btnUpload" value="Upload File" class="btn btn-primary" />
            td>


This post first appeared on ASPArticles, please read the originial post: here

Share the post

ASP.NET MVC file upload using Ajax jQuery in MVC

×

Subscribe to Asparticles

Get updates delivered right to your inbox!

Thank you for your subscription

×