How to upload multiple files in Node.js

Upload multiple files in Node.js

Before going to the practice part, I’ll show you a couple of things to notice.

In HTML, we need a form with: – action="/multiple-upload" – enctype="multipart/form-data" – multiple input

<form action="/multiple-upload" method="POST" enctype="multipart/form-data">
    ...
    <input type="file" multiple>
    ...
</form>

With the action "/multiple-upload" and POST method, we use Express Router for the endpoint and controller to handle upload files:

const express = require("express");
const router = express.Router();
const uploadController = require("../controllers/upload");

let routes = app => {
  router.post("/multiple-upload", uploadController.multipleUpload);
  return app.use("/", router);
};

The controller calls a middleware that uses Multerarrow-up-right disk storage engine:

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, '/path/to/uploads')
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now())
  }
});
 
var upload = multer({ storage: storage });

You can see that we have two options here: – destination determines folder to store the uploaded files. – filename determines the name of the file inside the destination folder.

Demo for upload multiple files

Open the app:

node-js-upload-multiple-files-demo-open-browser

Choose the images to upload:

node-js-upload-multiple-files-demo-choose-files

Click on Submit button, if the process is successful, you can see the files in upload folder:

node-js-upload-multiple-files-demo-upload-files-success

If the number of files we choose is larger than 10 (I will show you how to set the limit later):

node-js-upload-multiple-files-demo-upload-files-exceed

Practice

Now this is the time for building our app.

Project Structure

Look at the project structure:

node-js-upload-multiple-files-project-structure

You can see that we have these main parts: – upload: the folder for storing uploaded files. – views/index.html: contains HTML form for user to upload files. – routes/web.js: defines routes for endpoints that is called from views, use controllers to handle requests. – controllers: home.js to show views/index.html, upload.js to handle upload multiple files with middleware. – middleware/upload.js: initializes Multer disk storage engine. – server.js: initializes routes, runs Express app.

Setup Node.js modules

We need to install 2 packages: express and multer. So run the command: npm install express multer

Create view

Under views folder, create index.html:

The script above helps us show preview of the chosen files. To make things simple, I don’t explain it deeply in the tutorial.

Create middleware for upload multiple files

Inside middleware folder, create upload.js:

– We define a storage configuration object, then use multer module to initialize middleware and util.promisify() to make the exported middleware object can be used with async-await.

– To limit the number of files to upload each time, we use array() function with the first parameter is the name of input tag (in html view: <input type="file" name="multi-files">), the second parameter is the max number of files.

– We also check if the file is an image or not using file.mimetype. Then we add the [timestamp]-bezkoder- prefix to the file’s original name to make sure that the duplicates never occur.

If you want to do more, for example, resize the images, please visit this post: Upload & resize multiple images in Node.js using Express, Multer, Sharparrow-up-right

Create controllers

we create 2 files in controllers folder:

home.js

upload.js

Define routes

Under routes folder, define routes in web.js:

There are 2 routes: - GET: Home page for the upload form. - POST "/multiple-upload" to call the upload controller.

Create Express app server

The last thing to do is creating an Express server.

server.js

Run the app

On the project root folder, run this command: node src/server.js

The console shows:

Now you can open browser with url http://localhost:3000/ to check the result.

Last updated