Table of contents
- Prerequisites
- Setting Up the Project
- Express Server Code for Handling File Upload
- Key Points in the Server Code
- Running the Project
- Conclusion
In this article, we will go step-by-step through handling file uploads in a Node.js application using the express-fileupload [↗] package. There are several ways to handle file uploads in Express.js [↗], I however find using the express-fileupload package is much simpler and easier than most options.
Prerequisites
Before we get started, make sure you have Node.js [↗], this will also install NPM [↗] which we need for this tutorial.
We will also need the following packages:
- Express: A web framework for Node.js.
- express-fileupload: A middleware for handling file uploads.
Setting Up the Project
Install the Required Packages
Start by creating a new project folder, navigate into it from your terminal, and run the following command to initialize the project and install the necessary dependencies:
01: npm init -y 02: npm install express express-fileuploadTerminal
Set Up the Basic Structure
In your project folder, create two files:
server.js
: This file will contain your server-side code.index.html
: This file will contain the form to upload files.
HTML Form for File Upload
The HTML file contains a simple form that allows users to upload a file along with some additional information like their name and description. Here's what the form looks like:
index.html
01: <h1>Upload Form</h1>
02:
03: <form action="/submit" method="POST" enctype="multipart/form-data">
04: <input name="name" placeholder="name" />
05: <input name="description" placeholder="description" />
06: <input type="file" name="upload" />
07: <button type="submit">Submit</button>
08: </form>
This form sends the data to the /submit
route via a POST request. Notice the enctype="multipart/form-data"
attribute in the form tag—this is essential for uploading files.
Express Server Code for Handling File Upload
The server-side code is where the file upload happens. Below is the code for the server.js
file:
server.js
01: import express from 'express';
02: import path from 'path';
03: import fileUpload from 'express-fileupload';
04: import { fileURLToPath } from 'url';
05: import { promises as fs } from 'fs';
06:
07: const __filename = fileURLToPath(import.meta.url);
08: const __dirname = path.dirname(__filename);
09:
10: const app = express();
11: const port = 3000;
12:
13: // Middleware to handle file uploads
14: app.use(fileUpload());
15:
16: // Serve the HTML file
17: app.get('/', (req, res) => {
18: res.sendFile(path.join(__dirname, 'index.html'));
19: });
20:
21: // Handle file uploads and form submissions
22: app.post('/submit', async (req, res) => {
23: try {
24: const { name, description } = req.body;
25: let filePath = null;
26:
27: // Check if a file was uploaded
28: if (req.files && req.files.upload) {
29: const uploadObj = req.files.upload;
30: const uploadDir = path.join(__dirname, 'uploads');
31: filePath = path.join(uploadDir, uploadObj.name);
32:
33: // Create the uploads directory if it doesn't exist
34: await fs.mkdir(uploadDir, { recursive: true });
35:
36: // Move the file to the uploads directory
37: await uploadObj.mv(filePath);
38: }
39:
40: // Send response with file details
41: res.send(`
42: <b>Name:</b> ${name} <br>
43: <b>Description:</b> ${description} <br>
44: <b>File Path:</b> ${filePath ? `<a href="file://${filePath}" target="_blank">${filePath}</a>` : 'No file uploaded'}
45: `);
46: } catch (error) {
47: console.error('Error processing request:', error);
48: res.status(500).send('An error occurred while processing your request.');
49: }
50: });
51:
52: // Start the server
53: app.listen(port, () => {
54: console.log(`Server is running at http://localhost:${port}`);
55: });
Key Points in the Server Code
Setting Up the Middleware: The line
app.use(fileUpload());
[→] initializes express-fileupload middleware, which makes handling file uploads easy by providing access to uploaded files viareq.files
.Serving the HTML Form: The
app.get('/', ...)
[→] route serves theindex.html
file when a user visits the root of the site. This file contains the form for file upload.Handling File Uploads: The
app.post('/submit', ...)
[→] route handles the form submission. If a file is uploaded, it’s accessed viareq.files.upload
[→], whereupload
is thename
attribute from the form’s file input. The file is then moved to theuploads
directory usingmv()
, a function provided by express-fileupload.Dynamic File Path: After the file is uploaded, the server responds with a link to the uploaded file using the
file://
protocol. This allows users to open the file directly from their file system in the browser.
Running the Project
Start the server by running:
$ node server.jsOpen your browser and go to
http://localhost:3000
. You should see the file upload form.Upload a file and submit the form. You’ll receive a response showing the name, description, and a link to the uploaded file.
Conclusion
Hopefully you found this tutorial useful, if you happen to know an even easier way to upload files when working with Express.JS do let me know 😊.
Here is another article you might like 😊 MacOS AppleScript Tutorial: Part 4 – Advanced Automation And Real-World Examples