How to handle file upload in Expressjs

Step 1: Initiate the project

mkdir uploader && cd uploader
npm init -y

The first line creates an empty directory and moves into it. A new NodeJS project is initiated in this directory.

A package.json file is created with the default details.

The package.json file should look just like this:

{
  "name": "uploader",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

This configuration takes the name from the folder name. It also assumes that we have an index.js file as our main file.

Step 2: Create an ExpressJS server

Create a new index.js file and put the following code in it:

// Import dependencies
const express = require('express')
const app = express()
var bodyParser = require('body-parser')

// Set port
const port = 3000

// Register middlewares
app.use(bodyParser.urlencoded({ extended: false }))

// Home route
app.get('/', (req, res) => {
  res.send('Hello World!')
})

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

This file is our main application file. It requires a few dependencies that can be installed using:

npm i body-parser express
npm i -D nodemon

The first dependency, body-parser, is a middleware that adds the request data to the request. The dev dependency nodemon restarts the server whenever a change is made to the code, which ensures that the server is always running.

Now you have a new ExpressJS server ready to go. Run the server using nodemon.

nodemon index.js

Now the server is active and can listen for requests.

You can test by visiting http://localhost:3000 on your browser.

Step 3: Create a form view

Next, to handle file upload, a file has to be uploaded. To upload a file, an HTML form can be used.

Create an index.html file in the directory, at the same level as our main file, index.js, and add in the following content: