How To Use Multer to Upload Files in a Node.js REST API

Disclaimer: In an ideal scenario, uploaded images and files are typically stored on third-party services like Amazon S3, Cloudinary, or similar cloud storage providers. These services offer benefits such as scalability, reliability, and automatic handling of large file uploads. However, for the sake of this article, we are focusing on uploading files directly to the same server, stored locally in a dedicated folder (e.g., uploads/
). While storing files on the server can be convenient for smaller applications or during development, using cloud storage services is generally recommended for production environments to ensure better performance and scalability.
What is Multer?
Multer is a middleware that handles multipart/form-data
, which is used for uploading files. It processes the file data and makes it available in the req.file
or req.files
object, depending on whether you're handling single or multiple files. It integrates seamlessly with Express.js and is widely used for file upload functionality.
Steps to use Multer
Start by opening a terminal in you project workspace and install
multer
.npm install multer
In a well-structured Node.js REST API, it's a good idea to keep the code modular. Create a folder at the root of your project directory called
middlewares
if you don’t have it already and inside that create a file calledfileUpload.middleware.js
.Create another folder called
upload
(can be anything) to store the files. Here is how your project structure might look:my-node-app/ ├── node_modules/ ├── uploads/ # Folder for uploaded files ├── controllers/ # Controller files for handling business logic ├── middlewares/ │ └── fileUpload.middleware.js # Middleware folder to store all middlewares ├── models/ # Database models (if any) ├── routes/ # API route definitions ├── .env ├── index.js # Main entry point of the application ├── package.json └── package-lock.json
Open
fileUpload.middleware.js
and add following code snippet forDiskStorage
. Code snippets are available at multer’s npmjs page.const multer = require('multer') const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/') // mention the folder name, where you wants to upload your file. }, filename: function (req, file, cb) { const newFileName = Date.now() + '_' + file.originalname // rename the file to avoid any conflict. cb(null, newFileName) } }) const upload = multer({ storage: storage }) module.exports = upload
To get the filename and store it to database, in you controller function you can use -
let fileName = req.file.filename
In the router file use the file upload middleware and point to the controller for handling the uploaded file.
const upload = require('./../middlewares/fileUpload.middleware.js') postRouter.post("/posts", upload.single('field_name'), yourControllerFunction)
In order to serve the uploaded files (like images) stored in the uploads/
folder to users through the web, you need to set up that folder as a static asset in your Node.js application. This allows the server to serve the files directly when requested, rather than keeping them inaccessible.
In your index.js
file, use express.static()
to serve files from the uploads/
folder.
// index.js
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the "uploads" directory
app.use('/uploads', express.static(path.join(__dirname, 'uploads')
Hope this will help you in uploading files to the server.
Happy Coding!
Subscribe to my newsletter
Read articles from Surajit Das directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
