Join us on the demo, while our product experts provide a detailed walkthrough of our enterprise platform.
Get LoginRadius Swags in Hacktoberfest 2020. Check our hacktoberfest page for more details.

Upload files using NodeJS + Multer

Learn how to upload files in a NodeJS application using Multer, Multer is a middleware for handling multipart/form-data that is used to send files in forms.

Gabriel Rabelo
Gabriel Rabelo
October 12, 2020
2 min read

Introduction

When building APIs, the need to upload files is expected, which can be images, text documents, scripts, pdfs, among others. In the development of this functionality, some problems can be found, such as the number of files, valid file types, sizes of these files, and several others. And to save us from these problems we have the Multer library. Multer is a node.js middleware for handling multipart/form-data that is used to send files in forms.

First steps

The first step is to create a NodeJS project on your computer.

Adding Express

In your terminal, type the following command:

yarn add express

* You can also use NPM for installation

Create a file named app.js inside the src/ folder. The next step is to start our Express server in our app.js

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

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

Adding Multer

With the project created, configured and with Express installed, we will add the multer to our project.

yarn add multer

The next step is to import the multer into our app.js file.

const multer = require("multer")

We are almost there. Now create a folder called uploads where we will store the uploaded files.

Configuring and validating the upload

Now we are at a very important stage which is the configuration of diskStorage. DiskStorage is a method made available by multer where we configure the destination of the file, the name of the file and we can also add validations regarding the type of the file. These settings are according to the needs of your project. Below I will leave an elementary example of the configuration.

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

In the configuration above, we mentioned the destination for the uploaded files and also change the name of the file .

Providing an upload route

const uploadStorage = multer({ storage: storage })

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

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

In the code snippet above, we created 2 POST routes for sending files. The first /upload/single route receives only a single file, note that the uploadStorage variable receives our diskStorage settings. As a middleware in the route, it calls the single method for uploading a single file. The /upload/multiple route receives several files, but with a maximum limit of 10 files, note that the uploadStorage variable now calls the ʻarray` method for uploading multiple files.

The end

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

const express = require("express")
const multer = require("multer")

const app = express()

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

const uploadStorage = multer({ storage: storage })

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

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

Now it's up to you!



LoginRadius Docs

Implement Authentication in Minutes

click here

Most Popular Tags

EngineeringJavaScriptNodeJSCSSOAuthSecuritySocialLoginGoReactAuthentication

Are your customers safe on your application?

According to Forbes, data breaches exposed 4.1 billion records in the first six months of 2019. If this gets you worried, we have got your back!

LoginRadius protects your customers’ identities. We provide world class security for your customers during login, registration, password setup, and any other data touchpoints, and make sure that their data is safe. In parallel, it offers open source SDKs, integrations with over 150 third party applications, pre-designed and customizable login interfaces, and best-in-class data security products such as MFA, RBA, Advanced Password Policies. The platform is already loved by over 3,000 businesses with a monthly reach of 1.17 billion users worldwide.Secure Your Application Now

Gabriel Rabelo

Gabriel Rabelo

Passionate about programming and any type of technology.

View Profile

Try a Modern Authentication Solution

$0/ month

Free Sign Up
  • 5,000 MAU
  • 1 Web or mobile app
  • Standard login
  • 3 Social Login Providers
  • Transactional Email Template
  • Customizable Login Interfaces