Drag & drop file upload in ASP.NET MVC



Introduction

In one of my previous articles, I explained How to Upload Files Asynchronously using ASP.NET MVC application. Today I am going to show you how we can implement Drag & drop file upload in ASP.NET MVC application.

This is a very simple article today I am going to explain but Drag & drop file uploading is a very common requirement for any web application nowadays.  Drag and drop is a great HTML5 feature. So let Start implementing drag & drop file uploading in ASP.NET MVC application.

In this tutorial, we will see how to implement this using the FileDrop jQuery plugin.  jQuery FileDrop uses the HTML5 File API to allow users to drag multiple files from desktop to the browser, uploading each file to a user-specified URL.

Ok, let's start importing Drag & drop file upload in ASP.NET MVC. 

Follow the following steps in order to implement "Drag & drop file upload in ASP.NET MVC".

Here In this article, I have used Visual Studio 2015

Step - 1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Enter enter application name > select your project location > and then click on add button > It will brings up a new dialog window for select template > here I will select Empty template > checked  MVC checkbox from Add folder and core referances for: > and then click on ok button.

Step-2: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.
Here I have created a controller "HomeController"
Now we will add a view for Index action (which is already added in the home controller) where we will implement drag & drop file upload. 

Step-3: Add view for Index action.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select "Empty" under Template dropdown > Check use a layout page  > > Add.

HTML Code

@{
    ViewBag.Title = "Index";
}

<h2>Drag & Drop file upload </h2>
<div id="dropArea">
    Drop your files here
</div>
<h4>Uploaded files : </h4>
<ul class="list-group" id="uploadList">

</ul>

<style>
    #dropArea{
        background:#b5b5b5;
        border:black dashed 1px;
        height:50px;
        text-align:center;
        color:#fff;
        padding-top:12px;
    }
    .active-drop{
        background:#77bafa !important;
        border:solid 2px blue !important;
        opacity:.5;
        color:black !important;
    }
</style>

@section Scripts{    
    <script src="~/Scripts/jquery.filedrop.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#dropArea').filedrop({
                url: '@Url.Action("UploadFiles")',
                allowedfiletypes: ['image/jpeg', 'image/png', 'image/gif'],
                allowedfileextensions: ['.jpg', '.jpeg', '.png', '.gif'],
                paramname: 'files',
                maxfiles: 5,
                maxfilesize: 5, // in MB
                dragOver: function () {
                    $('#dropArea').addClass('active-drop');
                },
                dragLeave: function () {
                    $('#dropArea').removeClass('active-drop');
                },
                drop: function () {
                    $('#dropArea').removeClass('active-drop');
                },
                afterAll: function (e) {
                    $('#dropArea').html('file(s) uploaded successfully');
                },
                uploadFinished: function (i, file, response, time) {
                    $('#uploadList').append('<li class="list-group-item">'+file.name+'</li>')
                }
            })
        })
    </script>
}

Step-4: Update _Layout.cshtml page.

Here we will add a section for render script from another view. See the yellow marked lines.
   

<!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>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</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("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                </ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    @RenderSection("Scripts", required:false)
</body>
</html>

Step-5: Add jquery.filedrop.js from nuget.

Here in this article, we have used jquery.filedrop.js. We will add this js library into our application from NuGet.

Go to solution explorer > Right click on project name > Manage NuGet Packages... > Search with this keyword "jquery-filedrop" > Select and click Install button.

Step-6: Add an another Action in HomeController.

Add an another MVC action in the HomeController for upload file on the server.

[HttpPost]
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        string filePath = Guid.NewGuid() + Path.GetExtension(file.FileName);
        file.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), filePath));
        //Here you can write code for save this information in your database if you want
    }
    return Json("file uploaded successfully");
}

Step-7: Add a folder in your application

Now we will add a folder into our application where we will store uploaded files.

Go to Solution Explorer > Right Click on the project name > Add > New Folder.
I have renamed the folder as "UploadedFiles".


Step-8: Update web.config file.

This is required only when you want to allow more than 4MB file size.  Here I have allowed 5 MB (5120 KB).


Step-9: Run Application.

We have done all the steps. Now it's time to run the application. 

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.