ProgrammerGuide.Net | Step by Step Programmer Guide

Drag & Drop File Upload In ASP.NET MVC Using dropzone js with Fallback Browser Support | ASP.NET MVC Tutorial

Dropzone js library enables developer to add drag & drop file upload support in any web application very easily. This guide will add drag & drop file upload support in ASP.NET MVC application using dropzone js.

Why dropzone js?

  • It runs without jQuery or other JavaScript framework
  • It also handle old browser nicely and we can add fallback form elements which will be used in older browser
  • It supports image preview
  • Do not requires additional JavaScript code
Download dropzone js from here and include dropzone.js, css, images in MVC project and follow below step by step guide to add support for drag & drop file upload in ASP.NET MVC.

Step by Step Guide

First step is to include JavaScript & default CSS in MVC view as displayed in below code snippet.
<link href="~/Dropzone/css/basic.css" rel="stylesheet" />
<link href="~/Dropzone/css/dropzone.css" rel="stylesheet" />
<script src="~/Dropzone/dropzone.min.js"></script>

Once we linked above JS & CSS next step is to add form element. Best thing with dropzone js is that we just need to add form element with class “dropzone”, rest will be handled by dropzone js itself.
<form action="~/Home/SaveUploadedFile" method="post" 
    enctype="multipart/form-data" class="dropzone" 
    id="dropzoneForm">
</form>

As dropzone js is client library, it adds client side support in browser. For server side handling of uploaded file we need to write code for it. So below is the code snippet of how to handle uploaded file in MVC controller.
public ActionResult SaveUploadedFile()
{
    bool isSavedSuccessfully = true;
 
    foreach (string fileName in Request.Files)
    {
        HttpPostedFileBase file = Request.Files[fileName];
        //Save file content goes here
    }
 
    if (isSavedSuccessfully)
    {
        return Json(new { Message = "File saved" });
    }
    else
    {
        return Json(new { Message = "Error in saving file" });
    }
}

Yes we done for first test! Press Ctrl + F5 and navigate to view, we can see dropzone created where user can drag and drop file to upload it.
Dropzone also support image preview, drag some files in dropzone and you can see how it is uploaded to server along with image preview.

Handling Server Response

Now here we will see how we can handle server response with dropzone js. To handle server response, we need to add on complete event handler for dropzone. Below is the code snippet of how to add on complete event handler in dropzone.
<script type="text/javascript">
    Dropzone.options.dropzoneForm = {
        init: function () {
            this.on("complete", function (data) {                
                var res = eval('(' + data.xhr.responseText + ')');
                alert(res.Message);
            });
        }
    };
</script>

In on complete even handler, we can access XHR (XmlHTTPRequest) object with data.xhr. So in above code snippet we are accessing server response with data.xhr.responseText and parsing it into JSON and displaying it in browser. We can also get HTTP status of server request while upload files with data.status.

Fallback for older browser

We can add support for fallback browser very easily just by embedding container element with class “fallback” inside form element. Modify above HTML form markup with below markup to add support for older browser.
<form action="~/Home/SaveUploadedFile" method="post" 
    enctype="multipart/form-data" class="dropzone" 
    id="dropzoneForm">
    <div class="fallback">
        <input name="file" type="file" multiple />
        <input type="submit" value="Upload" />
    </div>
</form>

Now navigate to page through older browser and we can see file upload control.

Older Browser & Post Upload Redirection

Earlier we implemented action method which handle file upload on server side and return JSON object. While in case of older browser, on form submit, browser will be redirected to action URL but our earlier implementation sends JSON object as a response. So we need to modify that implementation so that in case of older browser, it sends HTML response. So below is the updated implementation of action method, which also handle older browser.
public ActionResult SaveUploadedFile()
{
    bool isSavedSuccessfully = true;
 
    foreach (string fileName in Request.Files)
    {
        HttpPostedFileBase file = Request.Files[fileName];
        //Save file content goes here
    }
 
    if (Request.IsAjaxRequest())
    {
        if (isSavedSuccessfully)
        {
            return Json(new { Message = "File saved" });
        }
        else
        {
            return Json(new { Message = "Error in saving file" });
        }
    }
    else
    {
        return RedirectToAction("PostUpload");
    }
}

Here we are checking if it is AJAX response then we are sending JSON object as response while in case of non-AJAX request it will return HTML response i.e. View Result and it will redirect browser to post upload view.

Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?