Saturday, 3 February 2018

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 .

Creating asp.net mvc 5 application

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

Selecting asp.net mvc 5 empty template

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

Asp.net mvc 5 empty folder structure

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;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.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
                    {
                        string fileName = Path.GetFileName(file.FileName);
                        string filePath = 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.

Addling index view

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 = '<div class="alert alert-success">' + response.responseMessage + '</div>';
                    }
                    else {
                        myhtml = '<div class="alert alert-danger">' + response.responseMessage + '</div>';
                    }
                    $("#myAlert").html(myhtml);
                    $("#myAlert").fadeIn(500).delay(3000).fadeOut(500);
                },
                error: function (error) {
                    $("#myAlert").html('<div class="alert alert-danger">' + error + '</div>');
                }
            });
        });
    });
</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 MVC</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                @Html.TextBox("fileID", "", new { type = "file" })
                @*<input type="file" name="file_Upload" id="fileID"/>*@
            </td>
            <td>
                <input type="submit" id="btnUpload" value="Upload File" class="btn btn-primary" />
            </td>

        </tr>
        <tr>
            <td colspan="2">
                <div id="myAlert">
                </div>
            </td>
        </tr>
    </tbody>
</table>

When application runs then view can be seen as below.

ASP.NET MVC file upload using Ajax jQuery in MVC

When you try to upload file other than excel file then below error will be shown.

Restrict files other than excel file in upload

When you upload excel file then file will be uploaded successfully.

Allow excel file to upload
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON

Ads By Chitika