Introduction
In this article, we learn how to upload multiple files in Node.js. We use multer libraries for uploading files in Node.js. In this article, we explain a very easy and simple way for beginner level, and explain with proper examples also attached a "rar" file to export your system and run it properly.
Steps for Creating a Project
Step 1. Set Up a Node.js Project
Use my previous article for setting up Node.js, "How to upload file in Node.js" In this article, we mentioned important commands for uploading files in Node.js.
Step 2. Project Structure.
When step one is completed, it creates some folders such as node modules, package-lock.json, and package.json, but we need to create some files below the image attached. The 'upload' folder is automatically created when the project is run, and all the uploaded files will upload to the 'upload' folder.
In this file structure, node_modules, package-lock.json, and package.json these files is created while you set up a project. We created index.js and views folder. Below attached all files used in this project.
Step 3. Create an index.js file.
In this file, have the "/" route and other necessary code required to run the project below the file is attached.
index.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const { render } = require('ejs');
var fs = require("fs");
const multer = require('multer');
const app = express();
// Middleware setup
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Set up static file serving for 'upload' folder
const uploadsPath = path.join(__dirname, 'upload');
app.use('/upload', express.static(uploadsPath));
// Route to render the 'first' view
/**
* @route GET /
* @description Render the 'first' view.
*/
app.get("/", function (req, res) {
res.render('first');
});
// Set up multer storage and upload configuration
const storage1 = multer.diskStorage({
destination: function (req, file, cb) {
// Check the fieldname and store files accordingly
if (file.fieldname === 'file1' || file.fieldname === 'file2' || file.fieldname === 'file3') {
cb(null, path.join(__dirname, '/upload'));
} else {
cb(new Error('Invalid field name'));
}
},
filename: (req, file, cb) => {
cb(null, file.originalname); // Use the original file name
}
});
const uploadd = multer({ storage: storage1 });
// Configure multer fields for file uploads
/**
* @typedef {Object} MulterField
* @property {string} name - The name of the field for file upload.
* @property {number} maxCount - The maximum number of files allowed to be uploaded for this field.
*/
/**
* @type {MulterField[]} fields - Multer fields configuration for file uploads.
*/
const cpUpload = uploadd.fields([
{ name: 'file1', maxCount: 1 },
{ name: 'file2', maxCount: 8 },
{ name: 'file3', maxCount: 8 }
]);
// Route to handle file upload
/**
* @route POST /fileupload
* @description Handle file upload.
* @returns {void}
* @throws {Error} If an invalid field name is provided.
*/
app.post('/fileupload', cpUpload, (req, res) => {
res.redirect('/');
});
// Start the server
/**
* @description Start the server and listen on port 3001.
* @event
*/
app.listen(3001, () => {
console.log('server is running on port http://localhost:3001');
});
Explanation
A server that can handle file uploads is created with the Node.js Express code that is provided. Multer, a well-known middleware library, is used to control file uploads. To render views, EJS is used as the templating engine. For the fields with the names "file1," "file2," and "file3," the application accepts file uploads. The 'upload' folder on the server is where the uploaded files are kept. Other developers will find it simpler to comprehend the functions of various routes and middlewares thanks to the inclusion of JSDoc comments in the code documentation. The 'first' view is rendered by the server at the root route, which operates on port 3001. When a file is successfully uploaded, the server returns users to the home page.
Step 4. Create first.ejs file.
This file has simple HTML and CSS code.
first.ejs
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
<style>
/* CSS styles for the file upload form */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
.container {
max-width: 400px;
margin: 0 auto;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="file"] {
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
width: 100%;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>File Upload</h2>
<!-- File upload form -->
<form action="/fileupload" method="post" enctype="multipart/form-data">
<!-- File 1 input -->
<div class="form-group">
<label for="file1">File 1:</label>
<input type="file" id="file1" name="file1">
</div>
<!-- File 2 input -->
<div class="form-group">
<label for="file2">File 2:</label>
<input type="file" id="file2" name="file2">
</div>
<!-- File 3 input -->
<div class="form-group">
<label for="file3">File 3:</label>
<input type="file" id="file3" name="file3">
</div>
<!-- Upload button -->
<input type="submit" value="Upload">
</form>
</div>
</body>
</html>
Explanation
Three file input fields are created in a file upload form using the specified HTML code. Users can upload files by choosing them and submitting the form. The form gains visual components thanks to the CSS styles. The chosen files are sent to the "/fileupload" endpoint using the "post" method and "multipart/form-data" encoding when the form is submitted. The uploaded files are processed by the server, which manages the endpoint. Developers can better understand and manage the functioning of the form by using the HTML comments, which offer succinct explanations of the code's function and organization.
Output
Conclusion
The Multer package is used in this article to demonstrate how to upload numerous files in a Node.js application. It provides examples to help users understand how to build up a Node.js project, create the file structure, and implement the file upload feature. The server configuration is handled by Express, and the templating engine is EJS. Users can submit files with specific names and size restrictions using Multer, which manages file uploads. For enhanced comprehension, JSDoc comments offer code documentation. An HTML file displaying a file upload form with three input fields is included with the article. This user-friendly manual gives programmers the tools they need to include effective multiple-file uploads in their Node.js apps.
FAQs
Q. What is the purpose of using Multer in this Node.js file upload article?
A. Multer is used to handle file uploads efficiently, enabling users to upload multiple files with specific names and maximum counts in the Node.js application.
Q. How does the article help beginners in setting up a Node.js project?
A. The article provides step-by-step instructions on setting up a Node.js project, creating the required file structure, and installing the necessary dependencies to implement file upload functionality.
Q. Can you explain the role of Express and EJS in this article?
A. Express is used to create the server and handle routes, while EJS serves as the templating engine for rendering the file upload form in the Node.js application.
Q. What are the benefits of using JSDoc comments in the code?
A. JSDoc comments serve as code documentation, helping developers understand the purpose and behavior of each route, middleware, and function in the application.
Q. How does the article ensure code readability and organization for multiple file uploads?
A. The article provides a clear file structure and well-documented JSDoc comments that explain the functionalities of different components, making it easier for developers to maintain and expand the file upload feature in the Node.js application.