File Upload in NodeJS with ExpressJS (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…
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.