In this tutorial ->

File uploads are a common requirement for many web applications. In this tutorial, we will explore how to handle file uploads in forms using Express.js. You will learn how to configure your Express application, handle multipart form data, and save uploaded files on the server.
By the end, you will have the knowledge to implement file upload functionality in your Express applications.
Setting up Express Project
1. Create a new directory for your project and navigate to it in your terminal:
mkdir express-app
cd express-app
2. Initialize a new npm project by running the following command and following the prompts:
npm init
3. Install Express as a dependency:
npm install express
4. Create a file named app.js (or any other preferred name) in the project directory. This will be the entry point of your Express application.
5. Open app.js in a code editor and add the following code to set up a basic Express application:
// Import the required modules
const express = require('express');
const app = express();
const port = 3000; // Choose your preferred port number
// Set up a route for the homepage
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
6. Save the file and go back to your terminal.
7. To start the Express application, run the following command:
node app.js
Once the server is up and running, you will see following message in the console:
‘Server is running on port 3000’
Open your web browser and visit http://localhost:3000 (replace 3000 with the port number you chose in the code). You should see the message “Hello, Express!” displayed in the browser.

You can stop this server by pressing CTRL+C.
Creating a Basic Form
In this step, we will create an HTML form that allows users to upload files.
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
Inside app.js, add the following code:
const path = require('path');
app.get('/', (req, res) => {
res.sendFile(__dirname+'/views/form.html');
});
This code sets up a route for the root path (“/”) that responds with an HTML form. The form has an input field of type “file” that allows users to select a file to upload. The form’s enctype attribute is set to "multipart/form-data" to handle file uploads.
Configuring File Uploads in Express
To handle file uploads, we need to configure Express to use a middleware that supports multipart form data. Install the multer package by running the following command:
npm install multer
Import and configure multer in app.js:
const multer = require('multer');
// Define the storage for uploaded files
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
// Create the multer middleware
const upload = multer({ storage: storage });
// Apply the middleware to the "/upload" route
app.post('/upload', upload.single('file'), (req, res) => {
// Handle the uploaded file here
});
In this code, we configure multer to use disk storage for uploaded files. The uploaded files will be stored in the “uploads/” directory, and their original names will be preserved.
The upload.single(‘file’) middleware is applied to the “/upload” route, specifying that we expect a single file upload with the field name “file”.
Handling File Uploads
Inside the route handler for “/upload”, we can access the uploaded file using req.file. For example, to log the file details, add the following code:
app.post('/upload', upload.single('file'), (req, res) => {
console.log('Uploaded file:', req.file);
res.send('File uploaded successfully!');
});
This code logs the file details to the console and sends a success message to the client.
Saving Uploaded Files
To save the uploaded files permanently, we need to handle file storage on the server. Create a directory named “uploads” in your project root to store the uploaded files.
Inside app.js, add the following line at the top to enable serving static files from the “uploads” directory:
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
This line ensures that files uploaded to the “uploads” directory are accessible through the “/uploads” URL path.
To display the uploaded file on a separate route, update the route handler for “/upload” as follows:
app.post('/upload', upload.single('file'), (req, res) => {
console.log('Uploaded file:', req.file);
res.send(`
<h2>File uploaded successfully!</h2>
<img src="/uploads/${req.file.filename}" alt="Uploaded file">
`);
});
This code responds with an HTML message and displays the uploaded file as an image. The req.file.filename variable is used to construct the URL for the uploaded file.
Handling Validation and Error Handling
When working with file uploads, it’s essential to validate the uploaded files and handle errors. For example, you might want to check the file type, size, or perform custom validation.
Inside the “/upload” route, add your custom validation and error handling logic. For instance:
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
res.status(400).send('No file uploaded!');
return;
}
});
In this code, we check if a file was uploaded and return an error response if no file was found. You can add your own validation checks or perform other necessary processing.
Starting our Application
1. To test the working of our application, run the following command
node app.js
2. If the above command is executed successfully, then, you will observe following message in the console:
Server is running on port 3000
3. Once you see the above message, navigate to ‘localhost:3000’ on your browser.
4. Let’s try to upload an image file by clicking on ‘Choose File’.
5. Click on upload.
6. As per our expectation,

7. Let’s see if there’s anything on our uploads directory.

Yup, an image was saved under uploads folder.
Congratulations! You’ve learned how to handle file uploads in forms using Express.js. We covered configuring file uploads, handling multipart form data, saving uploaded files, and handling validation and error scenarios. By applying this knowledge, you can enhance your Express applications with file upload functionality.
Keywords to search:
Express file upload tutorial,
Handling file uploads in Express.js,
Uploading files with forms in Express,
File upload example in Express,
Multer tutorial for Express file uploads,
Saving uploaded files in Express,
Validating file uploads in Express.js,
Express file upload middleware,
Handling multipart form data in Express,
Handling large file uploads in Express,
Express file upload best practices,
Secure file uploads in Express.js,
File upload progress in Express,
Limiting file size in Express file uploads,
Express file upload error handling,
Handling multiple file uploads in Express,
Streaming file uploads in Express.js,
Client-side file upload validation with Express,
Uploading files to cloud storage in Express,
Handling file uploads in Express and MongoDB,
