Integrating DropzoneJS into an ASP.NET MVC site

Dropzone allows you to easily handle file upload via drag and drop.

Here is a simple tutorial on how to integrate DropzoneJS into an existing ASP.NET MVC application. The instructions on the dropzone page are easy to follow but I include here a version tailored for ASP.NET MVC.

First off, there is a NuGet package but I prefer not to use it so that I can include only the necessary files and choose where those files are located.

The first step is to obtain the JavaScript file and include it into your /Scripts folder.

dropzone1

Optionally you can also download and use the CSS file. Put this one in your /Content folder.

dropzone2

Once these files are in place, it’s time to create some bundles. In App_Start/BundleConfig.cs add the following bundles:

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

bundles.Add(new StyleBundle("~/Content/dropzone-css")
            .Include("~/Content/dropzone.css"));

On the page you want to use dropzone on, add calls to the Styles and Scripts render methods and also a form element with the dropzone class. The class name is how dropzone locates the control so it can make the appropriate modifications.

Remember that you can’t nest form elements so if your page already contains another form your will need to make sure they aren’t nested.

Here is how our page.cshtml:

@Styles.Render("~/Content/dropzone-css")

<div class="jumbotron">
    <h1>dropzone test</h1>
</div>

<div class="row">
    @using (Html.BeginForm("FileUpload", "Home", 
                           FormMethod.Post,
                           new
                           {
                               @class = "dropzone",
                               id = "dropzone-form",
                           }))
    {
        <div class="fallback">
            <input name="file" type="file" multiple />
        </div>
    }
</div>

@section scripts {
    @Scripts.Render("~/bundles/dropzone")

    <script type="text/javascript">
        Dropzone.options.dropzoneForm = {
            paramName: "file",
            maxFilesize: 20,
            maxFiles: 4,
            acceptedFiles: "image/*",
            dictMaxFilesExceeded: "Custom max files msg",
        };
    </script>
}

The form contains an optional fallback element for clients who don’t support JavaScript. Also note in the scripts section, custom configuration options are declared.

You may notice I have set a maxFilesize. This value is in MB. It is necessary to change the maxRequestLength attribute in your web.config file to a value at least as big as maxFilesize, otherwise IIS will reject files under the maxFilesize limit.

Here is how to change your maxRequestLength:

<system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <!--maxRequestLength increased to 20 MB-->
    <httpRuntime targetFramework="4.5.2" 
                 maxRequestLength="20480" />
</system.web>

After we have updated our web.config we can now move on to the controller.

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
    try
    {
        var memStream = new MemoryStream();
        file.InputStream.CopyTo(memStream);

        byte[] fileData = memStream.ToArray();

        //save file to database using fictitious repository
        var repo = new FictitiousRepository();
        repo.SaveFile(file.FileName, fileData);
    }
    catch (Exception exception)
    {
        return Json(new { success = false, 
                          response = exception.Message });
    }

    return Json(new { success = true, 
                      response = "File uploaded." });
}

When uploading multiple files at the same time, this method will get called as many times as there are files.

If you want to handle the returned JSON, you need to handle events from dropzone, in this case the complete event.

Here is how the page looks after having uploaded two pictures:

dropzone3

6 thoughts on “Integrating DropzoneJS into an ASP.NET MVC site

  1. I have it working in both normal views and partial views in an ASP.NET MVC 5 project.

    You say it’s not working for partial views, have you tried it in a non partial view?
    What kind of behaviour are you getting? Any error messages? What do you see on the screen?

    1. Does the name of your HttpPostedFileBase parameter match the name attribute of your file input element in your markup?

      Does the name of your method match the name of the action in your BeginForm?

      Is the filesize of your file under both your maxRequestLength and maxFileSize?

    1. I haven’t touched this project in more than a year but from what I remember you can’t do that. It’s a control to upload files only.

      What I did in that project is that I put a file list above the dropzone control. The file list showed the previously uploaded files and dropzone was used to add more files. As the user would add files they would appear in the dropzone control.

      When the page was refreshed, the dropzone control would be empty but the file list would then be populated.

Leave a comment