How to handle file upload with Express

March 05, 2017

Uploading file is one of the most common thing in any web application. Let’s see how we can do that in less than 10 lines of code.

In Express it’s not pretty straight forward approach. So we’ll be using multer for handling file upload (multipart/form-data)

Step #1: Install dependencies

npm install --save express multer

Step 2: Set up your backend endpoint

const express = require(’express’)
const multer = require('multer')

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

app.post('/file-upload', upload.single('avatar'),(req,res) => {
  // req.file is the `avatar` file
  console.log(req.file);
  res.send(req.file)
})

app.listen(3000)

Step 3: Upload file from Client

In our cause we’ll be using Postman client for it.

file upload postman

Step 4: Here’s a gif for you

That moment works without any issues :)


👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP