Express.js / File Uploads and Multer in Express.js

Handling Multiple File Uploads

In this tutorial, we will delve into handling multiple file uploads using Multer in Express.js. We'll explore how to configure Multer to handle multiple files and how to process t…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores handling file uploads using Multer in Express applications.

1. Introduction

This tutorial aims to provide a comprehensive guide on handling multiple file uploads using Multer in Express.js. By following this tutorial, you will learn how to configure Multer to handle multiple files, process them in your routes, and gain a good understanding of how file uploads work in a server-side setting.

You will learn:
- How to set up Multer for multiple file uploads
- How to process uploaded files in your Express.js routes

Prerequisites:
- Basic knowledge of JavaScript and Node.js
- Familiarity with Express.js
- Installed Node.js and npm on your computer

2. Step-by-Step Guide

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for file uploads. It is built on top of busboy for maximum efficiency.

Setting up Multer

Install Multer via npm:

npm install --save multer

Require Multer and set up storage location and filename:

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname)
  }
})

const upload = multer({ storage: storage })

Handling Multiple Files

To handle multiple files, use the .array(fieldname[, maxCount]) method. Replace fieldname with the name attribute of the file input fields. maxCount is the maximum number of files to accept. If omitted, any number of files can be uploaded.

app.post('/upload', upload.array('myFiles', 12), (req, res, next) => {
  const files = req.files;
  if (!files) {
    const error = new Error('Please choose files')
    error.httpStatusCode = 400
    return next(error)
  }

  res.send(files)
})

3. Code Examples

Example: Uploading multiple files

// server.js
const express = require('express');
const multer = require('multer');
const app = express();

// configure storage
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage: storage });

// route to handle multiple files upload
app.post('/upload', upload.array('myFiles', 12), (req, res, next) => {
  const files = req.files;
  if (!files) {
    const error = new Error('Please choose files');
    error.httpStatusCode = 400;
    return next(error);
  }

  res.send(files);
});

app.listen(3000, () => console.log('Server started on port 3000'));

In this code snippet, we've set up an Express server that listens on port 3000. We've defined a POST route '/upload' that uses Multer's .array() method to handle multiple file uploads.

4. Summary

In this tutorial, you've learned how to set up Multer for handling multiple file uploads in an Express.js application. The next step would be to look into ways of validating the uploaded files (checking file types and sizes) and how to handle file upload errors.

Additional resources:
- Multer Documentation
- Express.js Documentation

5. Practice Exercises

  1. Exercise: Set up a new Express.js server, configure Multer for file uploads, and create a route to handle single file uploads.
    Solution: Refer to the code examples in this tutorial, but use the .single(fieldname) method instead of .array().

  2. Exercise: Modify the server you created in Exercise 1 to handle multiple file uploads. Limit the number of files that can be uploaded to 5.
    Solution: Use the .array(fieldname[, maxCount]) method and set maxCount to 5.

  3. Exercise: Add error handling to the file upload route. If the user does not upload any files, send a 400 error with a message 'Please choose files'.
    Solution: Add an if statement after declaring the files constant to check if any files were uploaded. If not, create a new Error object and pass it to the next function.

Remember, practice is the key to mastering any concept. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help