Node.js Upload Files

Why Handle File Uploads in Node.js?

Node.js is a popular choice for backend development because of its event-driven, non-blocking nature. It makes handling file uploads seamless, even for large files, by ensuring the server remains responsive during the upload process. With the help of middleware and libraries, you can quickly integrate file upload functionality into your Node.js applications.

Tools for File Uploads in Node.js

To handle file uploads effectively, you need a few tools:

  1. Express: A fast and minimal web framework for Node.js.
  2. Multer: A middleware for handling multipart/form-data, which is commonly used for file uploads.

You can install these tools using NPM:

npm install express multer

Setting Up the Project

Step 1: Create a New Project

Initialize a Node.js project:

npm init -y

Install the required packages:

npm install express multer

Step 2: Create a Basic Server

Start by creating a simple server using Express:

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

app.get('/', (req, res) => {
res.send('Welcome to the Node.js File Upload Tutorial!');
});

app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});

Run this code with:

node app.js

Visit http://localhost:3000 to see the server in action.

File Upload with Multer

Multer simplifies handling file uploads in Node.js. It parses incoming requests that contain files and stores them in your desired location.

Step 3: Set Up Multer for File Uploads

Here’s how to configure Multer:

  1. Import Multer in your project.
  2. Set up storage options to define where the files should be stored and how they should be named.
const multer = require('multer');

// Configure storage
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // Folder where files will be saved
},
filename: (req, file, cb) => {
const uniqueName = Date.now() + '-' + file.originalname;
cb(null, uniqueName); // Add timestamp to avoid overwriting files
},
});

// Initialize multer
const upload = multer({ storage });

Single File Upload

To upload a single file, use Multer’s upload.single() method.

Example: Single File Upload

app.post('/upload', upload.single('myFile'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}

res.send(`File uploaded successfully: ${req.file.filename}`);
});

Explanation:

  • Route: The /upload route listens for POST requests.
  • upload.single(‘myFile’): Handles a single file with the input field name myFile.
  • req.file: Contains information about the uploaded file (e.g., file name, path, size).

Multiple File Uploads

To upload multiple files, use Multer’s upload.array() method.

Example: Multiple File Uploads

app.post('/uploads', upload.array('myFiles', 5), (req, res) => {
if (!req.files || req.files.length === 0) {
return res.status(400).send('No files uploaded.');
}

const fileNames = req.files.map(file => file.filename);
res.send(`Files uploaded successfully: ${fileNames.join(', ')}`);
});

Explanation:

  • upload.array(‘myFiles’, 5): Allows up to 5 files to be uploaded with the input field name myFiles.
  • req.files: An array containing information about each uploaded file.

Creating the Upload Directory

Before running the above code, make sure you create an uploads folder in your project directory to store uploaded files:

mkdir uploads

File Validation

You can validate uploaded files based on their type or size using Multer’s fileFilter option.

Example: File Type Validation

const uploadWithValidation = multer({
storage,
fileFilter: (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Only image files are allowed!'), false);
}
},
});

app.post('/validate-upload', uploadWithValidation.single('image'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded or invalid file type.');
}

res.send(`Image uploaded successfully: ${req.file.filename}`);
});

Real-World Use Case

Imagine you’re creating a profile picture upload feature for a web app. Here’s how it would look:

HTML Form for Uploads

<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<label for="myFile">Upload File:</label>
<input type="file" name="myFile" id="myFile" />
<button type="submit">Upload</button>
</form>
</body>
</html>

Save this as index.html and serve it with your server. Users can upload files using this form.

Leave a Comment

BoxofLearn