Published on

How to handle file upload with Express

Authors

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.

Step 4: Here’s a gif for you

That moment works without any issues :)