0
0
ExpressHow-ToBeginner · 4 min read

How to Use Formidable in Express for File Uploads

To use formidable in express, first install it with npm install formidable. Then, create a route that uses formidable.IncomingForm() to parse incoming form data and files asynchronously inside your request handler.
📐

Syntax

The basic syntax to use formidable in Express involves creating a new IncomingForm instance and calling its parse method inside a route handler. The parse method takes the request object and a callback that receives any errors, the parsed fields, and the uploaded files.

Key parts:

  • const form = new formidable.IncomingForm(); - creates a new form parser.
  • form.parse(req, (err, fields, files) => { ... }) - parses the incoming request.
  • fields contains text inputs, files contains uploaded files.
javascript
const formidable = require('formidable');
const express = require('express');
const app = express();

app.post('/upload', (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, (err, fields, files) => {
    if (err) {
      res.status(400).send('Error parsing the files');
      return;
    }
    // Use fields and files here
    res.json({ fields, files });
  });
});
💻

Example

This example shows a complete Express server that accepts file uploads at /upload. It uses formidable to parse the form data and returns JSON with the uploaded file info.

javascript
import express from 'express';
import formidable from 'formidable';

const app = express();
const port = 3000;

app.post('/upload', (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, (err, fields, files) => {
    if (err) {
      res.status(400).send('Error parsing the files');
      return;
    }
    res.json({
      message: 'File uploaded successfully',
      fields: fields,
      files: files
    });
  });
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
Output
Server running on http://localhost:3000 // When a file is uploaded, response JSON example: // { // "message": "File uploaded successfully", // "fields": {"username": "john"}, // "files": {"file": {"filepath": "/tmp/upload_12345", "originalFilename": "photo.png", ...}} // }
⚠️

Common Pitfalls

Common mistakes when using formidable with Express include:

  • Not calling form.parse(req) properly, causing the request to hang.
  • Trying to access req.body before parsing, which will be empty because formidable handles parsing manually.
  • Not handling errors inside the parse callback, leading to uncaught exceptions.
  • Forgetting to set the form's upload directory or file size limits if needed.

Example of wrong usage:

app.post('/upload', (req, res) => {
  // Incorrect: accessing req.body before parsing
  console.log(req.body);
  res.send('Done');
});

Correct usage:

app.post('/upload', (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, (err, fields, files) => {
    if (err) {
      res.status(400).send('Error');
      return;
    }
    res.json({ fields, files });
  });
});
📊

Quick Reference

FeatureDescription
formidable.IncomingForm()Creates a new form parser instance
form.parse(req, callback)Parses incoming request to extract fields and files
fieldsObject containing text fields from the form
filesObject containing uploaded files with metadata
form.uploadDirSet directory to save uploaded files
form.maxFileSizeSet maximum allowed file size in bytes

Key Takeaways

Use formidable.IncomingForm() and call parse(req, callback) inside your Express route to handle file uploads.
Always handle errors inside the parse callback to avoid crashes.
Do not rely on req.body for file uploads; formidable parses the request manually.
Configure upload directory and file size limits on the form instance if needed.
Formidable works asynchronously and returns parsed fields and files in the callback.