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:
Create a new form using
new formidable.IncomingForm(). TheIncomingFormclass is the primary entry point to Formidable.Call
form.parse()on an Express request. This tells Formidable to parse the request and save any files in the request to your server.Handle the uploaded files. You can store the files locally, or upload the files to a service like Amazon S3.
Built an Express app and want to deploy it?
We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.
Deploy your Express app on Railway in minutes
We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.
Deploy your Express app on Railway in minutes
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!