28 Feb

File upload in ASP.NET MVC using Dropzone JS and HTML5

In this article we can learn how to file upload in asp.net mvc using Dropzone JS  and HTML . For this we will create a default asp.net mvc web application. Before jumping to the project, first we will download the dropzone js files.

File upload part 1: Limit Number of files upload using Dropzonejs Options – Part 1

File upload part 2: Removing thumbnails from dropzone js– Part 2

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

It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable.

You can download the latest version from the official site here http://www.dropzonejs.com/ and also we can install using the nuget package manage console by the following command Package Manager Console

PM> Install-Package dropzone

 File upload Implementation

After creating the default mvc project, install dropzone js using the nuget command.

install dropzone using nuget package

install dropzone using nuget package

Now create a bundle for your script file in  BundleConfig.cs

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

Similarly add the dropzone stylesheet  in the BundleConfig.cs

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

Now add the bundle reference in your _Layout page

dropzonelayout

dropzonelayout

Now every thing is fine now we can start writing up the application code. Now /Home/Index.cshtml file and Dropzone form in the page.

<div class="jumbotron">
    <form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
        <div class="fallback">
            <input name="file" type="file" multiple />
            <input type="submit" value="Upload" />
        </div>
    </form>
</div>

Now open the HomeController.cs and add the following code as follows

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)
                {

                    var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));

                    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");

                    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" });
            }
        }

Now add the following script to your Index.cshtml page

    //File Upload response from the server
        Dropzone.options.dropzoneForm = {
            init: function () {
                this.on("complete", function (data) {
                    //var res = eval('(' + data.xhr.responseText + ')');
                     var res = JSON.parse(data.xhr.responseText);
                });
            }
        };

Also add the following css

#dropZone {
        background: gray;
        border: black dashed 3px;
        width: 200px;
        padding: 50px;
        text-align: center;
        color: white;
    }

ASP.NET Web Forms Example

You can check the web forms source in the GitHub WebFormDropzoneDemo.aspx 

HTMLWebFormDropzoneDemo.aspx

Code: WebFormDropzoneDemo.aspx.cs

 Source Code

You can download the source from the Github

47 thoughts on “File upload in ASP.NET MVC using Dropzone JS and HTML5

  1. We are very impressed along with your writing abilities as well as using the structure for your blog page. Is that this your paid for topic or maybe did you colorize it for you oneself? At any rate stay on the wonderful good quality creating, it is actually exceptional to see a great web site exactly like it today.

  2. hi great work and great tutorial
    i have question how can i clear dropzone thumbnail image after uploading an image without refreshing the page

    • Suppose if any error occurs while saving you can set
      isSavedSuccessfully = false

      Example Below
      bool isSavedSuccessfully = true;
      string fName = "";

      try{
      //Save File here
      }
      catch(Exception ex)
      {
      isSavedSuccessfully = false;
      }

      if (isSavedSuccessfully)
      {
      return Json(new { Message = fName });
      }
      else
      {
      return Json(new { Message = "Error in saving file" });
      }

  3. Looks fine, but keep getting the error:
    >> This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet. <<
    why is that
    best regards Freddy

    • ASP.NET MVC framework blocks the HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you’ll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method.

      Example:
      return Json(new { Message = "Error in saving file" , JsonRequestBehavior.AllowGet});

  4. Hi this is great thanks. I am trying to allow users to upload images for a photo gallery, so the folder path will be generated and unique per gallery. How can you do this via a input field for example to allow a user to name the folder first, then the upload and create begins. All I need to display the galley is the file folder path (the only thing stored in database). Another option may be to dynamically generate a folder name each time?

    • I figured it out..

      so added a new input in view:

      Then in controller:

      change from: public ActionResult SaveUploadedFile()
      to: public ActionResult SaveUploadedFile(string folderName)

      and in the folder path, changed to:
      string pathString = System.IO.Path.Combine(originalDirectory.ToString(), folderName);

      works a treat! user generated foldernames, or can make it hidden field and generate folder name for them. (better option)

      very informative post thanks again

  5. Hello Venkat,
    I wanted to pass another text ( eg : Product Name ) with this controller… Could you please let me know how to do this …

    //<– I wanted to send this textbox values along with the image upload …

    • You can attach as input stream and can send email without saving the files in the server

      The following is the code to send attached files without storing these files on Server

      Code:
      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)
      {
      using (var mailMessage = new MailMessage())
      {
      mailMessage.From = new MailAddress(“**********@gmail.com”);
      mailMessage.Subject = “Subject”;
      mailMessage.Body = “Body”;
      mailMessage.IsBodyHtml = true;
      mailMessage.To.Add(new MailAddress(“*********@gmail.com”));

      //Add input file stream as attachment here and send the mail
      mailMessage.Attachments.Add(new Attachment(file.InputStream, Path.GetFileName(file.FileName), file.ContentType));

      var smtp = new SmtpClient {Host = “smtp.gmail.com”, EnableSsl = true};
      var networkCred = new System.Net.NetworkCredential
      {
      UserName = mailMessage.From.Address,
      Password = “************”
      };
      smtp.UseDefaultCredentials = true;
      smtp.Credentials = networkCred;
      smtp.Port = 587;
      smtp.Send(mailMessage);
      }
      }

      • Hi venkat,

        Thanks for your reply! i’m using dropzone inside existing form but no attachements files in my send mail with dropzone-previews. what I forgot?

        //here is my form:
        @using (Html.BeginForm(“confirmation-devis”, “fr”, FormMethod.Post, new { enctype = “multipart/form-data”, autocomplete = “on” }))
        {
        @Html.TextBoxFor(m => m.devisViewModel.Name, new { placeholder = “Name”, @class = “input-control first style”, tabindex = “5” })

        @Html.TextBoxFor(m => m.devisViewModel.Email, new { placeholder = “Email”, @class = “input-control style”, tabindex = “9” })

        //dropzone

        submit

        }

        //dropzone.js:

        Dropzone.prototype.defaultOptions = {
        url: ‘#’,
        method: “post”,
        withCredentials: false,
        parallelUploads: 100,
        uploadMultiple: true,
        maxFilesize: 256,
        paramName: “file”,
        createImageThumbnails: true,
        maxThumbnailFilesize: 10,
        thumbnailWidth: 100,
        thumbnailHeight: 100,
        maxFiles: 100,
        params: {},
        clickable: true,
        ignoreHiddenFiles: true,
        acceptedFiles: null,
        acceptedMimeTypes: null,
        autoProcessQueue: false,
        addRemoveLinks: false,
        previewsContainer: “.dropzone-previews”,
        },

        //scripts

        Dropzone.options.dropzoneForm = {
        init: function () {
        this.on(“complete”, function (data) {
        this.element.querySelector(“button[type=submit]”).addEventListener(“click”, function (e) {

        myDropzone.processQueue();
        });
        });
        }
        };

        $(“div#dropzoneForm”).dropzone({ url: “/fr/confirmation” });

        Many thanks!

  6. Hi,
    please help to me, how to increase the file size upload default values is 256Mb but it can not be working properly.Please mention example

          • Hello!

            I’m trying to get it to work using your new webForms solution. It looks beautiful but I get the error: “Server responded with 0 code.” and it seems like I don’t get a postback meaning the “page_load” never calls “SaveUploadedFile”. I’m trying to save the images uploaded in a database as bytes and I just can’t get it working.

            Any help would be hugely appreaciated.

          • Thank you venkat for Asp.net Example, but I’m uploading my image after I’m Changing my image name
            and I can’t take name the changing image, How can I get the name changed image ? For Remove !
            Thanks again..

          • Hello Venkat!

            Thank you for the quick responses.

            I have changed the URL to my *.aspx where the script is placed in the header, corresponding to WebFormDropzoneDemo.aspx. As you say, when I debug the application through Visual Studio SaveUploadedFile() is never called for some reason. Perhaps I’m misunderstanding what the url should be?

            Kind regards

  7. Hello,

    Why is the Request.Files always returns empty?

    controller
    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
    string fName = “”;

    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)
    {

    var originalDirectory = new DirectoryInfo(string.Format(“{0}Images\\WallImages”, Server.MapPath(@”\”)));

    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), “imagepath”);

    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);

    }

    }

    return View();
    }

    script:
    Dropzone.options.dropzoneForm = {
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    maxFilesize: 1, // MB
    addRemoveLinks: true,
    forceFallack: true,
    acceptedFiles: “.jpeg,.jpg,.png,.gif,.JPEG,.JPG,.PNG,.GIF”,
    maxFiles: 12,
    accept: function (file, done) {
    done();
    }
    };

    Any help is much appreciated,Thank You!

  8. I am getting Dropzone already attached in asp.net mvc
    I have already applied like
    Dropzone.autoDiscover = false;
    and
    Dropzone.options.myAwesomeDropzone = false
    but still having the issue.
    may be I am referencing the file more than once..
    looking for help..

    Thanks-
    Faiq

  9. I am implementing dropzone on ASP.NET mvc 6. It changed the server side implementation, have been able to migrate it the new version of ASP.NET?

  10. Someone knows how to display data from a model?

    public ActionResult SaveDropzoneJsUploadedFiles(ModelAlvaro model)
    {
    foreach (string fileName in Request.Files)
    {
    HttpPostedFileBase file = Request.Files[fileName];

    model.Mensaje= “put something here”;
    }

    //return to view whith data in the model
    return View(“Index”, model);
    }

    the problem is that data not shown …

    @if(Model !=null)
    {
    @Model.Mensaje;
    }

    Model have data, but dont display …

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>