DEV Community

Cover image for Upload files using NodeJS with Multer
Omor Faruk
Omor Faruk

Posted on • Edited on

Upload files using NodeJS with Multer

Discover how to use Multer—a middleware for managing multipart/form-data—to upload files into a NodeJS application. Files are sent via forms.

Introduction

It is common for files—images, text documents, scripts, PDFs, and more—to need to be uploaded when developing APIs. A number of issues, including the quantity of files, types of valid files, file sizes, and several others, have come up during the creation of this functionality. We also have the Multer library to help us avoid these issues. A node.js middleware called Multer is used to handle multipart/form-data, which is what forms utilize to transfer files.

Step 01

On your computer, start by creating a NodeJS project.

npm init -y

Add Express Dependency

Enter the following command into your terminal:

npm i express

Create a file named index.js inside the root folder. The next step is to start our Express server in our index.js

const express = require("express")
const app = express()

app.listen(3000 || process.env.PORT, () => {
  console.log("Server on...")
})
Enter fullscreen mode Exit fullscreen mode

Step 02 Including Multer

We will add the multiplier to our project once it has been established, configured, and Express has been installed.

npm i multer

Importing the multer into our index.js file is the next step.

import multer from 'multer';
Enter fullscreen mode Exit fullscreen mode

Setting up and confirming the upload

We are currently configuring diskStorage, which is a crucial step. Multiper provides a method called DiskStorage wherein we can specify the file's name, destination, and other validations related to its kind. These parameters are configured in accordance with your project's requirements. I've included a simple illustration of the arrangement below.

Create a middleware

Create a file createUploadImage.js inside a middlewares folder and add the following code:

import multer from 'multer';
import path from 'path';
import fs from 'fs';

const createUploadImage = (destination: string) => {
  const UploadImage = multer({
    limits: {
      fileSize: 5 * 1024 * 1024, // 5 MB file size limit
    },
    fileFilter: (req, file, cb) => {
      if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
        return cb(new Error('Only image files are allowed'));
      }
      cb(null, true);
    },
    storage: multer.diskStorage({
      destination: function (req, file, cb) {
        // Create the directory if it doesn't exist
        fs.mkdirSync(destination, { recursive: true });
        cb(null, destination);
      },
      filename: function (req, file, cb) {
        cb(null, `${Date.now()}${path.extname(file.originalname)}`);
      },
    }),
  });

  return UploadImage;
};

export default createUploadImage;

Enter fullscreen mode Exit fullscreen mode

In the configuration above, we mentioned the destination as a parameter for reuse uploaded files specific folder.

Giving a path for uploads

// Single file
app.post("/upload/single", createUploadImage.single("file"), (req, res) => {
  console.log(req.file)
  return res.send("Single file")
})

//Multiple files
app.post("/upload/multiple", createUploadImage.array("file", 10), (req, res) => {
  console.log(req.files)
  return res.send("Multiple files")
})
Enter fullscreen mode Exit fullscreen mode

We established two POST routes for file transfers in the code sample above. Only one file is received by the first /upload/single route; our diskStorage settings are received by the createUploadImage middleware. It calls the one method for uploading a single file as middleware in the route. The /upload/multiple route uploads several files, however notice that the createUploadImage variable now utilizes the \array} function for uploading multiple files, with a 10 file limitation.

The end

With all the settings done, our little API is already able to store the files sent.

import express from 'express';
import createUploadImage from './middlewares/upload.js';

const app = express();

const uploadSingle = createUploadImage('./uploads/single');
const uploadMultiple = createUploadImage('./uploads/multiple');

// Single file
app.post("/upload/single", uploadSingle.single("file"), (req, res) => {
  console.log(req.file);
  return res.send("Single file uploaded");
});

// Multiple files
app.post("/upload/multiple", uploadMultiple.array("file", 10), (req, res) => {
  console.log(req.files);
  return res.send("Multiple files uploaded");
});

app.listen(3000 || process.env.PORT, () => {
  console.log("Server on...");
});

Enter fullscreen mode Exit fullscreen mode

It's up to you now to expand this API and integrate it with your project!

Top comments (2)

Collapse
 
lotfijb profile image
Lotfi Jebali

Insightful and well explained thank you

Collapse
 
theonlineaid profile image
Omor Faruk

Thank You Mr. Lotfi Jebali