Friday, February 14, 2014

DropzoneJS with ASP.net MVC 5

Articles Of The Day


Introduction

  • This Article shows how to use DropzoneJS with your ASP.net MVC 5 Application.

What is DropzoneJS ?

  • DropzoneJS is an open source library that provides drag'n'drop file uploads with image previews.


Why DropzoneJS ?

  • It runs without jQuery or other JavaScript frameworks.
  • It supports image previews, that don't kill the browser if too many too big images are viewed.
  • Big files should get uploaded without a problem.
  • It uses the latest API of browsers and also handles older browsers nicely and you can add fallback form elements, which will be used in older browsers.

How to Use DropzoneJS with ASP.net MVC 5 ?

Step 1 :
  • Click below mentioned link to Download DropzoneJS Library.

DropzoneJS Download


Step 2 :
  • In Visual Studio 2013 create an ASP.net MVC 5 web application and name it as DropzoneJs.

Step 3 :
  • I have added DropzoneJS's CSS,Javascript and Image files into DropzoneJs Solution is as below.
DropzoneJS with ASP.net MVC 5


Step 4:
  • Open the bundleconfig.cs file for the project (inside the App_Start folder).
  • After that add the below mentioned bundles for it.
          An extract from bundleconfig.cs

            bundles.Add(new ScriptBundle("~/bundles/dropzone").Include(
                        "~/Scripts/dropzone.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                       "~/Content/bootstrap.css",
                       "~/Content/site.css",
                       "~/Content/basic.css",
                       "~/Content/dropzone.css"));

Step 5 :
  • Open the _layout.cshtml file for the project.
  • After that add the below mentioned code line at the bottom of the page and before the @RenderSection().
           @Scripts.Render("~/bundles/dropzone")


Step 6 :
  • The complete code for the Index.cshtml view is as below.

Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">

<form action="~/Home/SaveDropzoneJsUploadedFiles" class="dropzone" id="dropzoneJsForm"></form>

<button id="submit-all">Submit All Files</button>

</div>

@section scripts {
    <script type="text/javascript">

        Dropzone.options.dropzoneJsForm = {

            //prevents Dropzone from uploading dropped files immediately
            autoProcessQueue: false,

            init: function () {
                var submitButton = document.querySelector("#submit-all");
                var myDropzone = this; //closure

                submitButton.addEventListener("click", function () {
                    
                    //tell Dropzone to process all queued files
                    myDropzone.processQueue(); 
                });
                
            }
        };

    </script>
}


Key points of the above code
  • Need to add form element with class "dropzone" (i.e. class="dropzone"), rest will be handled by the DropzoneJS itself.
  • The id of the form also is very important here.That id's value will use with the Dropzone.options object in the JavaScript section (i.e. Dropzone.options.dropzoneJsForm).
  • You have to give the Controller Action method's name as the action attribute of the form element (i.e. action="~/Home/SaveDropzoneJsUploadedFiles").
  • You can use autoProcessQueue: false, to prevent DropzoneJS from uploading dropped files immediately.B'cos here in our example we use button's click event for saving the file details. 
  • submitButton.addEventListener("click") method to tell DropzoneJS to process all queued files when click the button.

Step 7 :
  • The Controller Action method is as below
        
          HomeController.cs

        /// <summary>
        /// to Save DropzoneJs Uploaded Files
        /// </summary>
        public ActionResult SaveDropzoneJsUploadedFiles()
        {
          bool isSavedSuccessfully = false;

          foreach (string fileName in Request.Files)
          {
             HttpPostedFileBase file = Request.Files[fileName];

             //You can Save the file content here

             isSavedSuccessfully = true;
          }

           return Json(new { Message = string.Empty });

        }


Key points of the above code
  • This code snippet is self explanatory.So it shows how to handle uploaded file in MVC controller.
  • Here you can use any file saving methodology as your preference.That may be a database,Azure cloud blob storage or folder etc.
  • You can add it on behalf of the code comment which I have put as like this  //You can Save the file content here

Step 7 :
  • That's it.You're done.Now let's run the App by pressing Ctrl + F5 keys.

DropzoneJS with ASP.net MVC 5



Step 8 :
  • When you click the above 'Drop files to upload' area, it pops up the below mentioned file selection dialog box.

DropzoneJS with ASP.net MVC 5






















Step 9 : 
  • When you click the 'Open' button from the above dialog box,All the selected files will show is as below.



DropzoneJS with ASP.net MVC 5


Step 10 : 
  • When you click the 'Submit All Files' button,you'll see the below kind of sentiment.



DropzoneJS with ASP.net MVC 5



That's it.You're done.


Do you need to Dive Deep ends of  DropzoneJS ?



Used Dev Environment in Article's Source Code

  • Visual Studio 2013 Express
  • .Net Framework 4.5.1
  • ASP.net MVC 5
  • C#


The source code for this Article


Conclusion

  • You realized that how easily you can configure the DropzoneJS with ASP.net MVC 5.
  • So enjoy the characteristics of this Awesome drag'n'drop file upload javascript library.

I hope this helps to You.Comments and feedback greatly appreciated.

If you feel it was a good article,Give me a +1.Thank You.



You Might Also Like

49 comments:

  1. Replies
    1. Hi Thabo,

      Thanks, I’m glad you enjoyed it ! :)

      Delete
  2. good guidance
    continue your duty
    i wish to you

    ReplyDelete
    Replies
    1. Hi Jeevalingam,

      You're warmly welcome.Thanks. :)

      Delete
  3. Wow Nice..I can even Add this to my Thesis Project System

    ReplyDelete
    Replies
    1. Hi Jenray,

      Thanks, I’m glad you found it useful ! :)

      Delete
  4. Nice one smapth about drop js and I will look deep in drop js what else we can do in drop js.

    ReplyDelete
    Replies
    1. Hi Anuj,

      Thanks. :)
      Yes you can do a lot by using this nice JS library.For more info please look into their home page.It's hear. http://www.dropzonejs.com/

      Delete
  5. Hello sampath ,

    This is interesting and usefull .
    Have you gone through to the deep of the implementation ?
    Is it asynchronus process ? or else
    Does it used iframe to upload ?
    How ever is there a page refresh while upload ?

    Its nice to see no jquery involvement . Usually Ajax cannot upload files . But lately XHR2 have introduced to this purpose ,yet sadly it is not supported by alll browsers.
    Its worth find the technology usage behind the scene and check browser compatibility of the plugin .




    ReplyDelete
    Replies
    1. Hi Hasitha,

      Thanks for your feedback.

      Your Q 1: Have you gone through to the deep of the implementation ?

      Ans 1 : I did this as a R&D task.So I never went through DJS's JavaScript implementation code base on Git hub.

      Your Q 2: Is it asynchronous process ? or else ?

      Ans 2 : Yes.Its Fully Asynchronous process.

      Your Q 3 : Does it used iframe to upload ?

      Ans 3 : There is No Iframe implementation.

      Your Q 4 : How ever is there a page refresh while upload ?

      Ans 4 : No. There is no page refresh while files upload.

      Note : It supports all the latest browsers and others which are starting from Chrome 7+,Firefox 4+ and IE 10+.For all the other browsers, dropzoneJs provides an old school file input fall-back.

      Delete
  6. Replies
    1. Hi Kranthi,

      Thanks, I’m glad you enjoyed it ! :)

      Delete
  7. How many files one can select at a time?

    ReplyDelete
    Replies
    1. Hi Alka,

      No, there is no such limit. You can apply any number of selections, if that permits the size of your storage media. :)

      Delete
  8. Please sir how to resize the image and drag the image from one location to another in canvas.

    ReplyDelete
    Replies
    1. Please read this.May be helped to you.
      http://davidwalsh.name/resize-image-canvas

      Delete
  9. Can you let me know y this is not working in IE 11 ? Do i have to change anything.

    ReplyDelete
    Replies
    1. Hi Anjali,

      It should work,according to their site's details.It says :

      BROWSER SUPPORT

      Chrome 7+
      Firefox 4+
      IE 10+
      Opera 12+ (Version 12 for MacOS is disabled because their API is buggy)
      Safari 6+

      Please check here : http://www.dropzonejs.com/

      Delete
    2. Yes it's working in their site but NOT in the application download which u have provided..

      Any help at the earliest would b greatful :)

      Delete
    3. Is this not working only with IE 11 or what ?

      Delete
    4. May be or may not be .. i dint check in other IE versions

      Delete
    5. Not IE.I mean other browsers such as Chrome,Firefox etc ..

      Delete
    6. OK. Then that is may be the browser compatibility issue.Please put your bug on SO.
      http://stackoverflow.com/tags/dropzone.js/hot

      Delete
  10. For adding more info , i get exception to break the application when i drag n drop any file when iam in IE browser.

    Exception at

    "dragover": function(e) {
    var efct;
    efct = e.dataTransfer.effectAllowed;
    e.dataTransfer.dropEffect = 'move' === efct || 'linkMove' === efct ? 'move' : 'copy';
    noPropagation(e);
    return _this.emit("dragover", e);
    },

    ReplyDelete
    Replies
    1. Hi Anjali,

      Please put your question on stackoverflow under the "dropzone.js" tag.You'll have quick response there. http://stackoverflow.com/tags/dropzone.js/hot

      Delete
  11. i wanted to know the code for storing the image in some URL, a free storage URL...please help...thanks

    ReplyDelete
    Replies
    1. Hi Khlood ,

      Where are you going to store the images (i.e database,Azure cloud blob storage or folder etc.) ?

      Delete
    2. Hi Khlood,

      There is no official SDK for .NET with regard to dropbox.But you can use ' HigLabo' library for interaction with the Dropbox.Please read below article for more info.It's for ASP.net web forms.But I hope you can get some knowledge about it and modify it to MVC app.I never try that though. :(

      Link : http://codingstill.com/2013/11/use-dropbox-with-your-asp-net-application/

      Good Luck ! :)

      Delete
    3. thanks alot sampath, i was going through a tutorial...could you help me out with this please? check it out please...
      http://sharpbox.codeplex.com/wikipage?title=SharpBox%20Developer%20Tutorials

      Delete
    4. the link that you provided has MVC implementation too :D :D look here
      http://buildstarted.com/2011/07/17/asp-net-mvc-3-file-uploads-using-the-fileapi/

      thanks!!! i'm trying this out, if i need help i'll comment here...

      Delete
  12. Have you implemented cancel files also

    ReplyDelete
    Replies
    1. Hi Srinivas,

      You can do that one pretty easily by using 'addRemoveLinks' options.If you want to remove all files, simply use .removeAllFiles(). Please check their API for more info : http://www.dropzonejs.com/

      Delete
  13. Dropzone:

    We are using dropzone in our MVC application.One of our requiremnt is to cancel Inprogress uploads.
    Currently we are uploading images and documents to sharepoint site.
    When we drag and drop images, we are displaying removes links for each image i.e. those images which
    are in progress with 'Cancel Upload' and queued files are with 'Remove Upload'.
    Here when we drag and drop images, Upload action (i.e. reaching the controller from js) is firing first and there after if you click on 'Cancel Upload'button, cancel action is calling.

    Working fine in local system but this is not working perfectly in azure environment and here we are unable to cancel Inprogress upload images.(cancelled images are uploaded to sharpeint site)

    We can able to remove images from dropzone and at the same time inprogress images are not cancelling properly from code behind(MVC controller action).

    Also Upload method is taking time to reach controller than cancel action.
    So, We verified the dropzone events and removed unnecessary dropzone code(removed progress bar code).

    We request you to provide solution for the above one as we need to cancel Inprogress images.

    The flow is like this.

    1.Once Drag and Drop image, then Upload controller action is firing.

    2.Image are with Cancel Upload button to cancel Inprogress upload.

    3.Once you clicked on Cancel Upload button, then Cancel action is firing.

    4.Here we are using HTTP web Request for file upload(chunk wise).

    ReplyDelete
  14. here code snippet:
    Code is given below.

    MVC Controller:

    public void Upload(HttpPostedFileBase file)
    {
    string key = string.Format("FileUploader{0}", file.FileName);
    try
    {
    AzureCache.Put(key, false);
    FileHelper fileUploader = new FileHelper();
    //Here we are using HTTP Web Request chunk wise upload
    fileUploader.Upload1(file.InputStream, file.FileName, key);
    System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(10).TotalMilliseconds);
    }
    catch (Exception ex)
    {
    }
    finally
    {
    AzureCache.Remove(key);
    }

    //return "File uploaded: " + file.FileName;
    }


    public string Cancel(string fileName)
    {
    string key = string.Format("FileUploader{0}", fileName);
    AzureCache.Put(key, true);

    return "File get canceled: " + fileName;
    }



    Dropzone.Js:


    $(document).ready(function () {

    Dropzone.options.frmUploader = {
    paramName: "file",
    maxFilesize: 10,
    init: function () {
    this.on("sending", function (file) {
    alert('Sending the file' + file.name)
    });

    this.on("complete", function (file) {
    alert("Completed: "+file.name);
    });

    this.on("removedfile", function (file) {
    alert("removedfile: "+file.name);
    });

    this.on("canceled", function (file) {

    $.get("Home/Cancel?fileName="+file.name, function (data) {
    $("#divResult").append(data);
    });

    //alert(file.name);
    });
    },
    addRemoveLinks: true,
    };
    });

    ReplyDelete
    Replies
    1. Hi srinivas,

      Please put your question here : http://stackoverflow.com/questions/tagged/dropzone.js with the Tag : dropzone.js

      or contact the author of DropzoneJs : G+ : https://plus.google.com/+MatiasMeno/posts OR Twitter : https://twitter.com/matenyo

      Good Luck ! :)

      Delete
  15. Hello Sampath Lokuge

    How can i modify the code so that i can save the uploaded pictures(file content) to the images folder of the application?

    this is based on the code comment that says: //You can Save the file content here

    ReplyDelete
    Replies
    1. //You can Save the file content here
      var fileSaveName = Path.GetFileName(file.FileName);
      file.SaveAs(Path.Combine(@"c:\YourProjectDirectory\YourApp\Images", fileSaveName));
      isSavedSuccessfully = true;

      Delete
  16. Great tutorial. Someone who has actually tested their code before posting. Great stuff! Thank you.

    ReplyDelete
  17. Excellent Post in Asp.net Mvc,
    Here i have similar article i.e. Asp.net Dropzonejs easy way to upload images c# with WebForms. Hope this will be helpfull for someone who need it in Asp.net Webforms.

    http://codepedia.info/2015/03/using-dropzone-js-file-image-upload-in-asp-net-webform-c/

    ReplyDelete
  18. Do we need to add enctype="multipart/form-data" in form tag?
    As i am getting only first image in Request.Files.

    ReplyDelete
  19. Very well explained about DropJS with ASP.Net.

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

    ReplyDelete
  21. Hello, how to implement dropzone in mvc 4 with entity framework

    ReplyDelete
  22. How can i modify the code so that i can save the uploaded pictures to the sql database?

    ReplyDelete

Thanks for your Feedback.