Wednesday, February 01, 2017

Drag and Drop file functionality in MVC 5 & HTML using dropzonejs

I was working on one of the requirement where i need to drag and drop files in MVC based application. I tried to googled and came across number of implementation. I came across following implementation which i like most and easy to implement.

I will try to explain the basic here how to use dropzonejs quickly.

  • Prequisites: We required following files for working example. both the files can be found and downloaded from here. Be sure to read warning message by Author.  
    • dropzone.js
    • dropzone.css
  • Steps:
    • Add these files in your MVC project.
      • .js => "Scripts/custom" folder
      • .css => "Content" folder
    • Modify the BundleConfig.cs files to add css files and javascript file
bundles.Add(new Scripts("~/bundles/dropzonescripts").Include(
                     "~/Scripts/custom/dropzone.js"));
bundles.Add(new Styles("~/Content/dropzonescss").Include(
                     "~/Content/Site.css",
                     "~/Content/dropzone.css"));
    • Render Css style using above bundle in _Layout.cshtml page "Head" Tag and render javascript  using above bundle in _Layout.cshtml page at bottom.

    • Add following div tag in page (in my case it was "FileTranslation\Index.cshtml" where you want to implement the Drag and Drop files facility.
      Note: FileTranslation is my controller name and SaveUploadedFile is my action. be sure to change if you have another name for controller and action.
<div class="jumbotron">
<form action="~/FileTranslation/SaveUploadedFile" class="dropzone" enctype="multipart/form-data" id="dropzoneForm" method="post">
<div class="fallback">
<input multiple="" name="file" type="file" />
            <input type="submit" value="Upload" />
        </div>
</form>
</div>
    • Add following script block in page where you have copied above code. Please make sure autoProcessQueue = true. This allows you to start transferring files automatically as soon as they dropped. if you want to manually upload filed make this parameter as false.
@section scripts {

    <script type="text/javascript">
        //File Upload response from the server
        Dropzone.options.dropzoneForm = {
            maxFiles: 2,
            autoProcessQueue: true,
            init: function () {
                this.on("complete", function (data) {
                    var res = eval('(' + data.xhr.responseText + ')');
                });
            }
        };
    </script>
}
    • Add following Action in "FileTranslation" Controller
      • Index()
      • SaveUploadedFile()
        private const string TempPath = @"C:\00-SandeepP";
        public ActionResult Index()
        {
            return View();
        } //Index()
        public ActionResult SaveUploadedFile()
        {
            bool isSavedSuccessfully = true;
            string fName = "";
            try
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];
                    //Save file content goes here
                    fName = file.FileName;
                    if (file != null && file.ContentLength > 0)
                    {
                       string pathString = System.IO.Path.Combine(TempPath);
                        

                        var fileName1 = Path.GetFileName(file.FileName);

                        bool isExists = System.IO.Directory.Exists(pathString);

                        if (!isExists)
                            System.IO.Directory.CreateDirectory(pathString);

                        var path = string.Format("{0}\\{1}", pathString, file.FileName);
                        file.SaveAs(path);
                    }
                }
            }
            catch (Exception ex)
            {
                isSavedSuccessfully = false;
            }

            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        } //SaveUploadedFile
    • Press F5 and you are ready to go to check your drag and drop files working