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

Uploading Files with Multer in Express.js

This tutorial will guide you through the process of setting up and using Multer in an Express.js application for file uploads. We'll cover the basics of Multer, how to configure i…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores handling file uploads using Multer in Express applications.

Uploading Files with Multer in Express.js

1. Introduction

In this tutorial, we'll learn how to upload files in an Express.js application using Multer, a Node.js middleware used for handling multipart/form-data, primarily used for file uploads.

By the end of this tutorial, you will be able to:
- Understand the fundamentals of Multer and its configurations.
- Implement a basic file upload function in Express.js using Multer.

Prerequisites:
- Basic knowledge of Node.js and Express.js.
- Node.js and NPM installed on your system.

2. Step-by-Step Guide

Multer is a middleware that simplifies file handling in Express.js. It provides functions to process files uploaded via HTML form upload (multipart/form-data).

Installing Multer
To start, install both express and multer using npm as shown below:

npm install express multer --save

Setting Up Multer
We need to import Multer and use it in our application. Let's define a storage location for our uploaded files, and initialize multer with that storage.

const express = require('express');
const multer = require('multer');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './uploads');
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  },
});

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

Here, we defined a storage location (./uploads) for our uploaded files. The filename function is used to maintain the original uploaded file's name.

3. Code Examples

Uploading a Single File
Let's create a post route where we can upload a file. We use the .single('file') function because we are uploading a single file. The 'file' argument corresponds to the name of the file input field in your HTML form.

app.post('/upload', upload.single('file'), (req, res, next) => {
  try {
    res.send(req.file);
  } catch (err) {
    res.send(400);
  }
});

In this function, req.file contains information about the uploaded file. If the upload was successful, we send back the req.file data, otherwise, we send a 400 error code.

Uploading Multiple Files
For multiple files, use the .array('files', maxCount) function. maxCount here is the maximum number of files allowed to be uploaded.

app.post('/uploadMultiple', upload.array('files', 10), (req, res, next) => {
  try {
    res.send(req.files);
  } catch (err) {
    res.send(400);
  }
});

In this function, req.files is an array of files uploaded.

4. Summary

In this tutorial, we learned how to use Multer for file upload in Express.js. We covered the installation of Multer, setting up Multer, and how to upload both single and multiple files. For further learning, explore Multer's documentation, and try to implement file validation and error handling.

5. Practice Exercises

  1. Exercise: Create an Express.js application and implement file upload using Multer.
    Solution: Follow the steps outlined in this tutorial to accomplish this. Practice changing the storage location and filename of the uploaded files.

  2. Exercise: Modify the application to upload multiple files at once.
    Solution: Use the .array('files', maxCount) function as shown in the multiple files upload section.

  3. Exercise: Implement a validation to allow only .png, .jpg, and .jpeg files.
    Solution: Use the fileFilter option in Multer's configuration. Check the file's mimetype and accept or reject the file based on whether it matches the accepted file types.

Remember, the key to becoming proficient in web development, like any other skill, is consistent practice and exploration. Keep experimenting with different features of Multer and Express.js. 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

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

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