How to Build a File Upload Form with Express and DropzoneJS

Share this article

How to Build a File Upload Form with Express and DropzoneJS

Let’s face it, nobody likes forms. Developers don’t like building them, designers don’t particularly enjoy styling them, and users certainly don’t like filling them in.

Of all the components that can make up a form, the file control could just be the most frustrating of the lot. It’s a real pain to style, it’s clunky and awkward to use, and uploading a file will slow down the submission process of any form.

That’s why a plugin to enhance them is always worth a look, and DropzoneJS is just one such option. It will make your file upload controls look better, make them more user-friendly, and by using AJAX to upload the file in the background, it will at the very least make the process seem quicker. It also makes it easier to validate files before they even reach your server, providing near-instantaneous feedback to the user.

We’re going to take a look at DropzoneJS in some detail. We’ll show how to implement it. and look at some of the ways in which it can be tweaked and customized. We’ll also implement a simple server-side upload mechanism using Node.js.

As ever, you can find the code for this tutorial on our GitHub repository.

This article was updated in 2020. For more on Node.js, read Node.js Web Development – Fourth Edition.

Introducing DropzoneJS

DropzoneJS allows users to upload files using drag and drop. Whilst the usability benefits could justifiably be debated, it’s an increasingly common approach and one which is in tune with the way a lot of people work with files on their desktop. It’s also pretty well supported across major browsers.

DropzoneJS isn’t simply a drag and drop based widget, however. Clicking the widget launches the more conventional file chooser dialog approach.

Here’s an animation of the widget in action:

The DropzoneJS widget in action

Alternatively, take a look at this most minimal of examples.

You can use DropzoneJS for any type of file, though the nice little thumbnail effect makes it ideally suited to uploading images in particular.

Features

To summarize some of the plugin’s features and characteristics, DropzoneJS:

  • can be used with or without jQuery
  • has drag and drop support
  • generates thumbnail images
  • supports multiple uploads, optionally in parallel
  • includes a progress bar
  • is fully themeable
  • includes extensible file validation support
  • is available as an AMD module or RequireJS module
  • comes in at around 43KB when minified and 13KB when gzipped

Browser Support

Taken from the official documentation, browser support is as follows:

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

There are a couple of ways to handle fallbacks for when the plugin isn’t fully supported, which we’ll look at later.

Getting Set Up

The simplest way to get started with DropzoneJS is to include the latest version from a CDN. At the time of writing, this is version 5.5.1.

Alternatively, you can download the latest release from the project’s GitLab page. There’s also a third-party package providing support for ReactJS.

Then, make sure you include both the main JavaScript file and the CSS styles in your page. For example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>File Upload Example</title>
  <link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css">
</head>
<body>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>
</body>
</html>

Note that the project supplies two CSS files — a basic.css file with some minimal styling, and a more extensive dropzone.css file. Minified versions of dropzone.css and dropzone.js are also available.

Basic Usage

The simplest way to implement the plugin is to attach it to a form, although you can use any HTML such as a <div>. Using a form, however, means fewer options to set — most notably the URL, which is the most important configuration property.

You can initialize it simply by adding the dropzone class. For example:

<form id="upload-widget" method="post" action="/upload" class="dropzone"></form>

Technically, that’s all you need to do, though in most cases you’ll want to set some additional options. The format for that is as follows:

Dropzone.options.WIDGET_ID = {
  //
};

To derive the widget ID for setting the options, take the ID you defined in your HTML and camel-case it. For example, upload-widget becomes uploadWidget:

Dropzone.options.uploadWidget = {
  //
};

You can also create an instance programmatically:

const uploader = new Dropzone('#upload-widget', options);

Next up, we’ll look at some of the available configuration options.

Basic Configuration Options

The url option defines the target for the upload form, and is the only required parameter. That said, if you’re attaching it to a form element then it’ll simply use the form’s action attribute, in which case you don’t even need to specify that.

The method option sets the HTTP method and again, it will take this from the form element if you use that approach, or else it’ll simply default to POST, which should suit most scenarios.

The paramName option is used to set the name of the parameter for the uploaded file. If you’re using a file upload form element, it will match the name attribute. If you don’t include it, it defaults to file.

maxFiles sets the maximum number of files a user can upload, if it’s not set to null.

By default, the widget will show a file dialog when it’s clicked, though you can use the clickable parameter to disable this by setting it to false, or alternatively you can provide an HTML element or CSS selector to customize the clickable element.

Those are the basic options, but let’s now look at some of the more advanced options.

Enforcing Maximum File Size

The maxFilesize property determines the maximum file size in megabytes. This defaults to a size of 1000 bytes, but using the filesizeBase property, you could set it to another value — for example, 1024 bytes. You may need to tweak this to ensure that your client and server code calculate any limits in precisely the same way.

Restricting to Certain File Types

The acceptedFiles parameter can be used to restrict the type of file you want to accept. This should be in the form of a comma-separated list of MIME types, although you can also use wildcards.

For example, to only accept images:

acceptedFiles: 'image/*',

Modifying the Size of the Thumbnail

By default, the thumbnail is generated at 120x120px. That is, it’s square. There are a couple of ways you can modify this behavior.

The first is to use the thumbnailWidth and/or the thumbnailHeight configuration options.

If you set both thumbnailWidth and thumbnailHeight to null, the thumbnail won’t be resized at all.

If you want to completely customize the thumbnail generation behavior, you can even override the resize function.

One important point about modifying the size of the thumbnail is that the dz-image class provided by the package sets the thumbnail size in the CSS, so you’ll need to modify that accordingly as well.

Additional File Checks

The accept option allows you to provide additional checks to determine whether a file is valid before it gets uploaded. You shouldn’t use this to check the number of files (maxFiles), file type (acceptedFiles), or file size (maxFilesize), but you can write custom code to perform other sorts of validation.

You’d use the accept option like this:

accept: function(file, done) {
  if (!someCheck()) {
    return done('This is invalid!');
  }
  return done();
}

As you can see, it’s asynchronous. You can call done() with no arguments and validation passes, or provide an error message and the file will be rejected, displaying the message alongside the file as a popover.

We’ll look at a more complex, real-world example later, when we look at how to enforce minimum or maximum image sizes.

Sending Additional Headers

Often you’ll need to attach additional headers to the uploader’s HTTP request.

As an example, one approach to CSRF (cross-site request forgery) protection is to output a token in the view, then have your POST/PUT/DELETE endpoints check the request headers for a valid token. Suppose you outputted your token like this:

<meta name="csrf-token" content="CL2tR2J4UHZXcR9BjRtSYOKzSmL8U1zTc7T8d6Jz">

Then, you could add this to the configuration:

headers: {
  'x-csrf-token': document.querySelector('meta[name=csrf-token]').getAttributeNode('content').value,
},

Alternatively, here’s the same example but using jQuery:

headers: {
  'x-csrf-token': $('meta[name="csrf-token"]').attr('content')
},

Your server should then verify the x-csrf-token header, perhaps using some middleware.

Handling Fallbacks

The simplest way to implement a fallback is to insert a <div> into your form containing input controls, setting the class name on the element to fallback. For example:

<form id="upload-widget" method="post" action="/upload" class="dropzone">
  <div class="fallback">
    <input name="file" type="file" />
  </div>
</form>

Alternatively, you can provide a function to be executed when the browser doesn’t support the plugin using the fallback configuration parameter.

You can force the widget to use the fallback behavior by setting forceFallback to true, which might help during development.

Handling Errors

You can customize the way the widget handles errors by providing a custom function using the error configuration parameter. The first argument is the file, the error message the second, and if the error occurred server-side, the third parameter will be an instance of XMLHttpRequest.

As always, client-side validation is only half the battle. You must also perform validation on the server. When we implement a simple server-side component later, we’ll look at the expected format of the error response, which when properly configured will be displayed in the same way as client-side errors (illustrated below).

Displaying errors with DropzoneJS

Overriding Messages and Translation

There are a number of additional configuration properties which set the various messages displayed by the widget. You can use these to customize the displayed text, or to translate them into another language.

Most notably, dictDefaultMessage is used to set the text which appears in the middle of the dropzone, prior to someone selecting a file to upload.

You’ll find a complete list of the configurable string values — all of which begin with dictin the documentation.

Events

There are a number of events you can listen to in order to customize or enhance the plugin.

There are two ways to listen to an event. The first is to create a listener within an initialization function:

Dropzone.options.uploadWidget = {
  init: function() {
    this.on('success', function(file, resp){
      ...
    });
  },
  ...
};

This is the alternative approach, which is useful if you decide to create the Dropzone instance programatically:

const uploader = new Dropzone('#upload-widget');
uploader.on('success', function(file, resp){
  ...
});

Perhaps the most notable aspect is the success event, which is fired when a file has been successfully uploaded. The success callback takes two arguments: the first a file object, and the second an instance of XMLHttpRequest.

Other useful events include addedfile and removedfile, for when a file has been added or removed from the upload list; thumbnail, which fires once the thumbnail has been generated; and uploadprogress, which you might use to implement your own progress meter.

There are also a bunch of events which take an event object as a parameter and which you could use to customize the behavior of the widget itself — drop, dragstart, dragend, dragenter, dragover and dragleave.

You’ll find a complete list of events in the relevant section of the documentation.

A More Complex Validation Example: Image Dimensions

Earlier we looked at the asynchronous accept() option, which you can use to run checks (validation) on files before they get uploaded.

A common requirement when you’re uploading images is to enforce minimum or maximum image dimensions. We can do this with DropzoneJS, although it’s slightly more complex.

Although the accept callback receives a file object, in order to check the image dimensions we need to wait until the thumbnail has been generated, at which point the dimensions will have been set on the file object. To do so, we need to listen to the thumbnail event.

Here’s the code. In this example, we’re checking that the image is at least 640x480px before we upload it:

init: function() {
  this.on('thumbnail', function(file) {
    if (file.accepted !== false) {
      if (file.width < 1024 || file.height < 768) {
        file.rejectDimensions();
      }
      else {
        file.acceptDimensions();
      }
    }
  });
},
accept: function(file, done) {
  file.acceptDimensions = done;
  file.rejectDimensions = function() {
    done('The image must be at least 1024 by 768 pixels in size');
  };
},

A Complete Example

Having gone through the options, events, and some slightly more advanced validation, let’s look at a complete and relatively comprehensive example. Obviously we’re not taking advantage of every available configuration option, since there are so many — making it incredibly flexible.

Here’s the HTML for the form:

<form id="upload-widget" method="post" action="/upload" class="dropzone">
  <div class="fallback">
    <input name="file" type="file" />
  </div>
</form>

If you’re implementing CSRF protection, you may want to add something like this to your layouts:

<head>
  <!-- -->
  <meta name="csrf-token" content="XYZ123">
</head>

Now the JavaScript. Notice we’re not using jQuery!

Dropzone.options.uploadWidget = {
  paramName: 'file',
  maxFilesize: 2, // MB
  maxFiles: 1,
  dictDefaultMessage: 'Drag an image here to upload, or click to select one',
  headers: {
    'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
  },
  acceptedFiles: 'image/*',
  init: function() {
    this.on('success', function(file, resp){
      console.log(file);
      console.log(resp);
    });
    this.on('thumbnail', function(file) {
      if (file.accepted !== false) {
        if (file.width < 640 || file.height < 480) {
          file.rejectDimensions();
        }
        else {
          file.acceptDimensions();
        }
      }
    });
  },
  accept: function(file, done) {
    file.acceptDimensions = done;
    file.rejectDimensions = function() {
      done('The image must be at least 640 x 480px')
    };
  }
};

A reminder that you’ll find the code for this example on our GitHub repository.

Hopefully this is enough to get you started for most scenarios. Check out the full documentation if you need anything more complex.

Theming

There are a number of ways to customize the look and feel of the widget, and indeed it’s possible to completely transform the way it looks.

As an example of just how customizable the appearance is, here’s a demo of the widget tweaked to look and feel exactly like the jQuery File Upload widget using Bootstrap.

Obviously the simplest way to change the widget’s appearance is to use CSS. The widget has a class of dropzone and its component elements have classes prefixed with dz- — for example, dz-clickable for the clickable area inside the dropzone, dz-message for the caption, dz-preview / dz-image-preview for wrapping the previews of each of the uploaded files, and so on. Take a look at the dropzone.css file for reference.

You may also wish to apply styles to the hover state — that is, when the user hovers a file over the dropzone before releasing their mouse button to initiate the upload. You can do this by styling the dz-drag-hover class, which gets added automatically by the plugin.

Beyond CSS tweaks, you can also customize the HTML that makes up the previews by setting the previewTemplate configuration property. Here’s what the default preview template looks like:

<div class="dz-preview dz-file-preview">
  <div class="dz-image">
    <img data-dz-thumbnail />
  </div>
  <div class="dz-details">
    <div class="dz-size">
      <span data-dz-size></span>
    </div>
    <div class="dz-filename">
      <span data-dz-name></span>
    </div>
  </div>
  <div class="dz-progress">
    <span class="dz-upload" data-dz-uploadprogress></span>
  </div>
  <div class="dz-error-message">
    <span data-dz-errormessage></span>
  </div>
  <div class="dz-success-mark">
    <svg>REMOVED FOR BREVITY</svg>
  </div>
  <div class="dz-error-mark">
    <svg>REMOVED FOR BREVITY</svg>
  </div>
</div>

As you can see, you get complete control over how files are rendered once they’ve been queued for upload, as well as success and failure states.

That concludes the section on using the DropzoneJS plugin. To round up, let’s look at how to get it working with server-side code.

A Simple Server-side Upload Handler with Node.js and Express

Naturally, you can use any server-side technology for handling uploaded files. In order to demonstrate how to integrate your server with the plugin, we’ll build a very simple example using Node.js and Express.

To handle the uploaded file itself, we’ll use Multer, a package that provides some Express middleware that makes it really easy. In fact, this easy:

const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res, next) => {
  // Metadata about the uploaded file can now be found in req.file
});

Before we continue the implementation, the most obvious question to ask when dealing with a plugin like DropzoneJS, which makes requests for you behind the scenes, is: “what sort of responses does it expect?”

Handling Upload Success

If the upload process is successful, the only requirement, as far as your server-side code is concerned, is to return a 2xx response code. The content and format of your response is entirely up to you, and will probably depend on how you’re using it. For example, you might return a JSON object which contains a path to the uploaded file, or the path to an automatically generated thumbnail. For the purposes of this example, we’ll simply return the contents of the file object — that is, a bunch of metadata provided by Multer:

return res.status(200).send(req.file);

The response will look something like this:

{ fieldname: 'file',
  originalname: 'myfile.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: 'uploads/',
  filename: 'fbcc2ddbb0dd11858427d7f0bb2273f5',
  path: 'uploads/fbcc2ddbb0dd11858427d7f0bb2273f5',
  size: 15458 }

Handling Upload Errors

If your response is in JSON format — that is to say, your response type is set to application/json — then the DropzoneJS default error plugin expects the response to look like this:

{
  error: 'The error message'
}

If you aren’t using JSON, it’ll simply use the response body. For example:

return res.status(422).send('The error message');

Let’s demonstrate this by performing a couple of validation checks on the uploaded file. We’ll simply duplicate the checks we performed on the client. Remember, client-side validation is never sufficient on its own.

To verify that the file is an image, we’ll simply check that the MIME type starts with image/. ES6’s String.prototype.startsWith() is ideal for this.

Here’s how we might run that check and, if it fails, return the error in the format which Dropzone’s default error handler expects:

if (!req.file.mimetype.startsWith('image/')) {
  return res.status(422).json({
    error: 'The uploaded file must be an image'
  });
}

Note: I’m using HTTP Status Code 422, Unprocessable Entity, for validation failure, but 400 Bad Request is just as valid. Indeed, anything outside of the 2xx range will cause the plugin to report the error.

Let’s also check that the image is of a certain size. The image-size package makes it really straightforward to get the dimensions of an image. You can use it asynchronously or synchronously. We’ll use the latter to keep things simple:

const dimensions = sizeOf(req.file.path);

if ((dimensions.width < 640) || (dimensions.height < 480)) {
  return res.status(422).json({
    error: 'The image must be at least 640 x 480px'
  });
}

Let’s put all of it together in a complete (mini) application:

const express = require('express');
const multer = require('multer');
const upload = multer({ dest:'uploads/'});
const sizeOf = require('image-size');
const exphbs = require('express-handlebars');

const app = express();

app.use(express.static(__dirname +'/public'));

app.engine('.hbs', exphbs({ extname:'.hbs'}));
app.set('view engine','.hbs');

app.get('/', (req, res) => {
  return res.render('index', {layout: false});
});

app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file.mimetype.startsWith('image/')) {
    return res.status(422).json({
      error :'The uploaded file must be an image'
    });
  }

  const dimensions = sizeOf(req.file.path);

  if ((dimensions.width < 640) || (dimensions.height < 480)) {
    return res.status(422).json({
      error :'The image must be at least 640 x 480px'
    });
  }

  return res.status(200).send(req.file);
});

app.listen(8080, () => {
  console.log('Express server listening on port 8080');
});

Note: for brevity, this server-side code doesn’t implement CSRF protection. You might want to look at a package like CSURF for that.

You’ll find this code, along with the supporting assets such as the view, in the accompanying repository.

And if you’d like to learn more about working with forms in Node.js, please read Forms, File Uploads and Security with Node.js and Express.

Summary

DropzoneJS is a slick, powerful and highly customizable JavaScript plugin for supercharging your file upload controls and performing AJAX uploads. In this tutorial, we’ve taken a look at a number of the available options, at events, and how to go about customizing the plugin. There’s a lot more to it than can reasonably be covered in one tutorial, so check out the official website if you’d like to know more. But hopefully this is enough to get you started.

We’ve also built a really simple server-side component to handle file uploads, demonstrating how to get the two working in tandem.

Frequently Asked Questions (FAQs) about File Upload Form with Express and Dropzone.js

How Can I Customize the Appearance of My Dropzone?

Dropzone.js provides a default layout that you can customize to match your website’s design. You can modify the CSS file included in the Dropzone library to change the appearance of the dropzone area. For instance, you can change the border style, color, and hover effects. Additionally, you can customize the preview template to change how the uploaded files are displayed.

How Can I Limit the File Size for Uploads?

Dropzone.js allows you to set a maximum file size for uploads. You can do this by setting the ‘maxFilesize’ option when initializing your Dropzone. The size is specified in megabytes. For example, to set a limit of 2MB, you would use ‘maxFilesize: 2’.

Can I Upload Multiple Files at Once?

Yes, Dropzone.js supports multiple file uploads. By default, multiple file uploads are enabled. If you want to limit the number of files that can be uploaded at once, you can set the ‘maxFiles’ option when initializing your Dropzone.

How Can I Handle Upload Errors?

Dropzone.js provides several events that you can listen to in order to handle errors. For instance, the ‘error’ event is fired when an upload fails. You can use this event to display an error message to the user or to take other actions.

Can I Use Dropzone.js with Other Form Fields?

Yes, you can integrate Dropzone.js with other form fields. You can do this by disabling the auto process queue and manually submitting the form. When the form is submitted, you can process the Dropzone queue and other form data together.

How Can I Remove an Uploaded File?

Dropzone.js provides a method called ‘removeFile’ that you can use to remove an uploaded file. You can call this method with the file object that you want to remove as an argument.

Can I Preview Images Before Uploading?

Yes, Dropzone.js automatically generates previews for image files. You can customize the appearance of these previews by modifying the preview template.

How Can I Translate Dropzone.js Messages?

Dropzone.js allows you to customize all displayed messages. You can do this by setting the ‘dictDefaultMessage’, ‘dictFallbackMessage’, ‘dictFileTooBig’, and other options when initializing your Dropzone.

Can I Use Dropzone.js Without jQuery?

Yes, Dropzone.js does not depend on jQuery or any other library. It is a standalone library and can be used with any other JavaScript library or framework.

How Can I Install Dropzone.js?

You can install Dropzone.js by downloading the library from the official website or by using a package manager like npm or Bower. After downloading, you can include the Dropzone.js and Dropzone.css files in your HTML file.

Lukas WhiteLukas White
View Author

Lukas is a freelance web and mobile developer based in Manchester in the North of England. He's been developing in PHP since moving away from those early days in web development of using all manner of tools such as Java Server Pages, classic ASP and XML data islands, along with JavaScript - back when it really was JavaScript and Netscape ruled the roost. When he's not developing websites and mobile applications and complaining that this was all fields, Lukas likes to cook all manner of World foods.

drag & dropExpressform validationjameshnodenode-hubNode-JS-Tutorialsnode.js
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week