Menu Close

How to Accept File Uploads with Express?

To accept file uploads in our Express apps, we can use the multer Express middleware.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
const multer = require('multer');
const upload = multer({ dest: 'uploads/' })

app.get('/', (req, res) => {
  res.send('hello world')
});

app.post('/', upload.single('file'), (req, res) => {
  console.dir(req.file);
  res.send('uploaded')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to add the multer Express middleware.

To install it, we run:

npm i multer

Then to make the POST / route accept a file upload.

We call upload.single with the key of the form to get the file.

Then we can get the uploaded file with the req.file property.

The file will be stored in the /uploads folder as set as the value of the dest property.

Then if we make a request to the POST / route with a form data object that has the file key set to a file, the file will be uploaded.

Posted in Express, expressjs