HTML5 Zone is brought to you in partnership with:

My name is Pieter De Rycke, I am a Belgian technical .Net architect working in the insurance sector. I am always eager to learn new technologies and I like to keep up with the latest innovations and trends in the IT sector. I am a big believer in web services for interoperability between platforms. Pieter is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

Implementing HTML5 Drag & Drop Based File Upload in ASP.NET MVC 3

05.24.2012
| 30019 views |
  • submit to reddit

Introduction

HTML5 makes it possible to develop more powerful and more user friendly web applications than we could do ever before. One of the interesting new features is support for drag and drop of files. In the past, if your application needed to provide the possibility to upload files you had to use a file selection chooser. Although this works without issues in all browsers, it is far from user friendly. In native applications, users can interact with files by using drag and drop which is much more intuitive. Luckily for us, HTML5 now also supports this and it is already supported in a number of browsers (Chrome, Firefox, Safari, …).

In this article, I will show you how we can implement drag & drop in an ASP.NET MVC3 web application. We will create a webpage containing a simple drop area that changes of color when the user is dragging a file over the page and we will update the content of the page if the file upload was successful. In order to implement the client side code, we will make use of jQuery and a jQuery plugin called “jquery-filedrop” that simplifies implementing drag & drop based file upload.

You can download “jquery-filedrop” from:
https://github.com/weixiyen/jquery-filedrop

Implementation

We start by creating a new ASP.NET MVC 3 web application and we add the file “jquery-filedrop.js” to the Scripts folder of the project. After this is done we modify the default layout “Views/Shared/_Layout.cshtml” to reference our newly added JavaScript library. In order to do is, add the following line to the head tag.

<script src="@Url.Content("~/Scripts/jquery.filedrop.js")" type="text/javascript"></script>

I also choose to upgrade to the latest version of jQuery with NuGet; but this is not strictly required…

Now that everything is in place, we can start writing our applicative code. First create a HomeController and an “Index” view for this controller.

Solution View

In the view we will create a div with the id “dropZone”. This will be the area in which users can drop files. Next, we will write some jQuery code that will make the div “droppable”. Thanks to the jQuery plugin we are using, the required code for this is trivial. We just have to call the method “filedrop” with a number of needed parameters.

For our sample application, we provide the URL for the file upload, the parameter name of the files to be used in the HTTP POST, the maximum allowed number of files that can be upload simultaneously and we will listen to some events to add some dynamic behavior to the page. More specifically, if the user is dragging a file over the page we will change the color of the drop zone and we will update a list of successfully updated files.

@{
    ViewBag.Title = "Index";
}
<style type="text/css">
    #dropZone {
        background: gray;
        border: black dashed 3px;
        width: 200px;
        padding: 50px;
        text-align: center;
        color: white;
    }
</style>
<script type="text/javascript">
    $(function () {
        $('#dropZone').filedrop({
            url: '@Url.Action("UploadFiles")',
            paramname: 'files',
            maxFiles: 5,
            dragOver: function () {
                $('#dropZone').css('background', 'blue');
            },
            dragLeave: function () {
                $('#dropZone').css('background', 'gray');
            },
            drop: function () {
                $('#dropZone').css('background', 'gray');
            },
            afterAll: function () {
                $('#dropZone').html('The file(s) have been uploaded successfully!');
            },
            uploadFinished: function (i, file, response, time) {
                $('#uploadResult').append('<li>' + file.name + '</li>');
            }
        });
    });
</script>

<h2>File Drag & Drop Upload Demo</h2>
<div id="dropZone">Drop your files here</div>
<br/>
Uploaded Files:
<ul id="uploadResult">

</ul>

Now that the view is in place, we can add the required method to our HomeController in order to support the file upload. I choose to call this method “UploadFiles”, it must have a parameter named files (the one we choose in the configuration of our drop zone) and the parameter must be of type “IEnumerable<HttpPostedFileBase>”. In order to keep things simple, we will just write the files to some temporary folder. But of course you can do whatever you want with the uploaded files…

public class HomeController : Controller
{
    private const string TempPath = @"C:\Temp";

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (HttpPostedFileBase file in files)
        {
            string filePath = Path.Combine(TempPath, file.FileName);
            System.IO.File.WriteAllBytes(filePath, ReadData(file.InputStream));
        }

        return Json("All files have been successfully stored.");
    }

    private byte[] ReadData(Stream stream)
    {
        byte[] buffer = new byte[16 * 1024];

        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }

            return ms.ToArray();
        }
    }
}
 

Conclusion

Now al what rest us, is pressing F5 and testing the application in a browser that already supports this HTML5 specification. I have tested this in the latest version of Google Chrome and Firefox.

image

As I have shown you, it is very easy to implement file drag and drop behavior into your web application, but of course you will still have to support a legacy mechanism as well for people with older browsers.

You can download my sample from:
https://skydrive.live.com/redir?resid=7A3CD9AFBD57E81E!428

Published at DZone with permission of Pieter De Rycke, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)