File Upload in NodeJS with ExpressJS (2020)

Overview

Louis.Z
2 min readAug 23, 2020

Today’s web application often enable user to upload photos, videos, files to it. The data are large and needs to be handled differently from standard forms.

Setup

Setup the project…

npm init -y

Install both ExpressJS and Multer dependencies…

npm i express multer

Code

I will go through the steps in parts for better understanding.

Step 1: Setup server-side — index.js that return a basic html for uploading.

Running node index.js, you will be able to see the following…

Step 2: Setup Multer

Add Multer and path library

const multer = require(‘multer’);
const path = require(‘path’);

Setup storage destination — Upload folder destination can be customized via the callback function. Similarly, the filename can be customized as by default, multer removes the file extension.

Connect it as ExpressJS middleware —

Final Looks with error handling — multer(…).single(…) returns a function and the third parameter can be passed in for error handling.

Testing

Running through the web application…

1. Choose a file to upload
2. Success message after uploading
3. File can be found in Nodejs tmp folder

Thanks to Multer, a full uploading functionlity can be created with just a few lines of code. Multer also support uploading of multiple files which I will cover that in a future article.

--

--

Louis.Z

A passionate software engineer with strong background in web technology, product development and design architecture.