File Uploads with Express

May 22, 2019

Formidable is the most popular file uploading library for Express. Here's how you can use Formidable to upload files:

const app = require('express')();
const formidable = require('formidable');
const fs = require('fs');

app.post('/upload', function(req, res) {
  const form = new formidable.IncomingForm();
  // Parse `req` and upload all associated files
  form.parse(req, function(err, fields, files) {
    if (err != null) {
      console.log(err)
      return res.status(400).json({ message: err.message });
    }

    // The `files` object contains all files that were uploaded. Formidable
    // parses each file and uploads it to a temporary file for you.
    const [firstFileName] = Object.keys(files);

    res.json({ filename: firstFileName });
  });
});

const server = await app.listen(3000);

The /upload route handler has 3 steps:

  1. Create a new form using new formidable.IncomingForm(). The IncomingForm class is the primary entry point to Formidable.

  2. Call form.parse() on an Express request. This tells Formidable to parse the request and save any files in the request to your server.

  3. Handle the uploaded files. You can store the files locally, or upload the files to a service like Amazon S3.


Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials