
- Node.js - Home
- Node.js - Introduction
- Node.js - Environment Setup
- Node.js - First Application
- Node.js - REPL Terminal
- Node.js - Command Line Options
- Node.js - Package Manager (NPM)
- Node.js - Callbacks Concept
- Node.js - Upload Files
- Node.js - Send an Email
- Node.js - Events
- Node.js - Event Loop
- Node.js - Event Emitter
- Node.js - Debugger
- Node.js - Global Objects
- Node.js - Console
- Node.js - Process
- Node.js - Scaling Application
- Node.js - Packaging
- Node.js - Express Framework
- Node.js - RESTFul API
- Node.js - Buffers
- Node.js - Streams
- Node.js - File System
- Node.js MySQL
- Node.js - MySQL Get Started
- Node.js - MySQL Create Database
- Node.js - MySQL Create Table
- Node.js - MySQL Insert Into
- Node.js - MySQL Select From
- Node.js - MySQL Where
- Node.js - MySQL Order By
- Node.js - MySQL Delete
- Node.js - MySQL Update
- Node.js - MySQL Join
- Node.js MongoDB
- Node.js - MongoDB Get Started
- Node.js - MongoDB Create Database
- Node.js - MongoDB Create Collection
- Node.js - MongoDB Insert
- Node.js - MongoDB Find
- Node.js - MongoDB Query
- Node.js - MongoDB Sort
- Node.js - MongoDB Delete
- Node.js - MongoDB Update
- Node.js - MongoDB Limit
- Node.js - MongoDB Join
- Node.js Modules
- Node.js - Modules
- Node.js - Built-in Modules
- Node.js - Utility Modules
- Node.js - Web Module
Node.js - Upload Files
The Node.js is a good choice for handling the files-upload, Because of its non-blocking nature and ability to efficiently manage the concurrent requests.
In a Node.js application, the file uploading involves sending the files from the client (browser) to a server over HTTP. The server then processes the files, stores them in a specified location, or perform some action based on them. For this process, we will use the two main tools they are:
- Express − It is a minimal web framework for handling the HTTP requests and responses.
- Multer − It is a middleware that makes it easy to handle file uploads in Express.
Setting Up the Project
Initializing the Project
The first step is to set up the project folder, initialize it with the NPM and install the dependencies. Use the following command to create a new folder and navigate to it:
mkdir file-test cd file-test
Then, Initialize the Node.js application with npm:
npm init -y
This will generate a package.json with the default values.
Now, we are going to install the necessary dependencies (express and mutter), use the following command to install them:
npm install express multer
Project Structure
Importing Dependenciesconst express = require('express'); const multer = require('multer'); const path = require('path'); const fs = require('fs');
Here we are going to import the :
- express for creating the server and handle the requests
- multer for handling the file uploads
- path to work with the file paths (getting the file extensions).
- fs for interacting with the file system.
const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, './test'); }, filename: (req, file, cb) => { cb(null, Date.now() + path.extname(file.originalname)); }, });
In the following Multer storage we have used:
- destination − It defines the folder where the uploaded files will be stored.
- filename − It defines the name of the uploaded file and we are also going to use the current timestamp along with the original file extension.
const upload = multer({ storage: storage });
Here, we are going to make the Multer to use the custom storage configuration, which we set up.
Creating the 'test' Folderif (!fs.existsSync('./test')) { fs.mkdirSync('./test'); }
Before we are going to handle the uploads, we make sure that the test folder exists. If it doesnt exist, we will create it by using the fs.mkdirSync().
Handling File Uploads (POST Route)app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded'); } res.send(`File uploaded successfully: ${req.file.filename}`); });
In this we are going to use the:
- upload.single − It tells the multer to handle the single file upload from the field named file in the form.
- req.file − If the upload gets successful, the file details will be stored in the req.file.
app.get('/', (req, res) => { res.send(` <h1>Upload a File</h1> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <button type="submit">Upload</button> </form> `); });
This GET route serves as the simple HTML form where the user can select a file and upload it.
Starting the Serverapp.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
This starts the express server and listens on port 1121. The console will log a message indicating that the server is up and running.
Creating the Server
Let's create a file named 'tp.js' in the project directory, Which will set up the Express server and handle file uploads.
tp.jsconst express = require('express'); const multer = require('multer'); const path = require('path'); const fs = require('fs'); const app = express(); const port = 1121; const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, './test'); }, filename: (req, file, cb) => { cb(null, Date.now() + path.extname(file.originalname)); }, }); const upload = multer({ storage: storage }); if (!fs.existsSync('./test')) { fs.mkdirSync('./test'); } app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded'); } res.send(`File uploaded successfully: ${req.file.filename}`); }); app.get('/', (req, res) => { res.send(` <h1>Upload a File</h1> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <button type="submit">Upload</button> </form> `); }); app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
Running the Server
For starting the server, run the following command in the terminal:
node tp.jsOutput
Output of the above command is as follows −
Server is running at http://localhost:1121
Now, you can visit the http://localhost:1121 in your browser, Where you can find the upload form to choose a file and upload it to the server.
Additional Features
We can also extend this basic file upload setup in the several ways, Let's look some of them.
File Size Limit
In the following case, we are going to limit the size of the file using the limits option.
const upload = multer({ storage: storage, limits: { fileSize: 10 * 1024 * 1024 } });
Here we set the limit to 10Mb and When we use this, it will reject the files that exceeds the size limit.
Multiple File Uploads
When we are in a need to upload the multiple file instead of single file at once, use the upload.array() instead of upload.single().
app.post('/upload', upload.array('x', 4), (req, res) => { if (!req.x) { return res.status(400).send('No files uploaded'); } res.send(`Successfully uploaded ${req.x.length} files`); });
In this case, we are going to allow the user to upload 4 files at once, and also change the input field of the HTML form as shown below:
<input type="file" name="x" multiple required />