node js multiple files upload

·

2 min read

Now a days most of the guys are working on open source technologies which is almost free even we don't need to pay to use most of the software. We can contribute to open source by sharing our knowledge in a different ways like create you tube channel, write blog, contribute on github repositories, answers on stack overflow and so on

Today I will show you how can we handle multiple file upload in express JS

First we will have to setup express JS in our system. If you are new to express JS then you can refer my previous blog first four points are how we can setup express in our system

How we can upload multiple files in node JS

install multiparty package in our application. This package is used to manage multipart form data.

npm install --save multiparty

in our controller setup a route to serve file upload page in which two or three file upload fields will be available:

controller route to serve ejs file:

Untitled (1).jpeg

our html will look like:

Untitled (3).jpeg

Now the code to upload multiple files

Untitled (5).jpeg

here our route name is multiplefileupload and we are importing multiparty package in our second line

Then we are parsing form using form.parse. this method has a callback in which three parameters exist. error means in case of any error in form parsing. fields parameters is for all the fields which are not multipart and the third one is files (which is multipart form fields)

in line 13 we are checking if path not exist we are creating a path by fs.mkdirSync(newPath) which is node js file system method. after that we are change our file name to unique name using current timestamp. then we have a method like readAndWriteFile in which first parameter is image instance and second parameter is the path in which we want to upload file.