File uploading in Node.js

In this article, we’ll explore how to handle file uploading in the Node.js application. File uploading is a very commonly used feature in node js web applications, it allows users to upload files such as images, videos, documents, and many more. Here we will discuss this using Multer middleware , one of the most popular methods to upload files in Node.js

 

Using Multer Middleware

Multer is a popular middleware for handling file uploads in Node.js. it is commonly used with the express to simplify its process by receiving and submitting HTTP requests. Multer parses the incoming multiware/form-data and makes the uploaded files easily accessible as objects in requests. It also allows you to control how and where to store the received files on the server

Install Multer using this command :

npm install multer  

After installing the  Multer, import it to your Node.js

Example: Configuring Multer

const multer = require('multer');  

// Configure storage  
const storage = multer.diskStorage({  
  destination: (req, file, cb) => {  
    cb(null, 'uploads/'); // Directory to save uploaded files  
  },  
  filename: (req, file, cb) => {  
    cb(null, `${Date.now()}-${file.originalname}`);  
  },  
});  

const upload = multer({ storage });  

This configuration saves flies to an “uploads/” directory with timestamped filename.

Handling Single File Uploads

To handle single files we use the upload.single() method, and by specifying the name of the dorm field that contains the file.

Example: Single file upload

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

app.post('/upload', upload.single('file'), (req, res) => {  
  res.send(`File uploaded successfully: ${req.file.filename}`);  
});  

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

 

Output:

When a file is uploaded, it well be saved in “uploads/” directory, and then the server will respond with its file name

 

Handling Multiple File Uploads

 

To handle multiple files we use the upload.array() method. This is useful to forms that ask users to upload multiple files simultaneously.

Example: Multiple File Uploads

app.post('/upload-multiple', upload.array('files', 5), (req, res) => {  
  const fileNames = req.files.map(file => file.filename);  
  res.send(`Files uploaded successfully: ${fileNames.join(', ')}`);  
});  

Output:

If you upload 3 files the response will be like this:

Files uploaded successfully: 16614664-image1.jpg, 16749481-image2.png, 167884545-image3.pdf

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top