a blog for those who code

Saturday 3 January 2015

Drag'n'Drop file uploads in Asp Net MVC Application using DropzoneJS

In this post we will show you how to integrate DropzoneJS in AspNet MVC application. DropzoneJS is an open source library that provides drag'n'drop file uploads with image previews. It's a lightweight and doesn't depend on any other library.

PC : http://www.dropzonejs.com/

Importance of using DropzoneJS is that it runs without jQuery or any other javaScript library thus making it a lightweight process. If any browser (IE9, IE8 etc) does not support drag'n'drop feature, it is possible to add fallback form elements thus making it a good option to use.

Download DropZone.js from here and include dropzone.js, css and images in your project.

Integrate DropZoneJS In ASPNET MVC Application

At first create a MVC Internet Application and add contents of Dropzone in the application as shown below.
After that add below contents to your Index.cshtml

// Include Javascript & default CSS
<link href="~/Content/css/basic.css" rel="stylesheet" />
<link href="~/Content/css/dropzone.css" rel="stylesheet" />
<script src="~/Content/dropzone.js" type="text/javascript"></script>

//Add form element with post and class="dropzone" along with a div (class="fallback") to support old browser
<form action="~/Home/Index" method="post" enctype="multipart/form-data" class="dropzone" id="DropZoneDemo">
    <div class="fallback">
       <input name="file" type="file" multiple />
        <input type="submit" value="Upload" />

// Show Server response when the file gets uploaded
<script type="text/javascript">
    Dropzone.options.DropZoneDemo = {
        init: function () {
            this.on("complete", function (data) {
                var res = eval('(' + data.xhr.responseText + ')');

And change the HomeController.cs as

public ActionResult Index()
    if (Request.Files.Count > 0)
         var isFileSaved = true;
         foreach (string file in Request.Files)
            HttpPostedFileBase httpPostedfileBase = Request.Files[file];
            String path = Server.MapPath("~/Uploads/");
// Save File to Upload folder
                httpPostedfileBase.SaveAs(path + httpPostedfileBase.FileName);
                 isFileSaved = false;
           return (isFileSaved == true ? Json(new { Message = "File Saved" }, JsonRequestBehavior.AllowGet) : Json(new { Message = "Error in Saving File. Try Again" }, JsonRequestBehavior.AllowGet));
            return View();

When you will run your application you can see the working of DropzoneJS

When you upload files using DropzoneJS you will to see the output as below.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

1 comment:

  1. Hello friend How i can ingrate dorpzone jquery with existing from have many inputs in asp.net mcv