Implementing file uploads in a Node.js application can be done using various packages and modules. One popular choice is the multer
middleware, which simplifies the process of handling multipart/form-data for file uploads. Here's a step-by-step guide on how to implement file uploads in a Node.js application using Express and Multer:
Initialize a Node.js Project: If you don't have a Node.js project already, create one by running the following commands in your terminal:
bashmkdir my-file-upload-app
cd my-file-upload-app
npm init -y
Install Dependencies: Install the necessary dependencies, including Express and Multer:
bashnpm install express multer
Create an Express App:
Create a basic Express application in a file (e.g., app.js
):
javascriptconst express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;
// Set up Multer for handling file uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/'); // Set the destination folder for uploaded files
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname); // Set the file name
},
});
const upload = multer({ storage: storage });
// Set up a route for file uploads
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully!');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Create an Upload Form:
Create an HTML form to allow users to upload files. You can use a simple form with the enctype
attribute set to "multipart/form-data"
:
html<!-- upload.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
Serve the HTML Form:
Modify your app.js
to serve the HTML form when the root URL is accessed:
javascript// ...
// Serve the HTML form
app.get('/', (req, res) => {
res.sendFile(__dirname + '/upload.html');
});
// ...
Run the Application: Run your Node.js application:
bashnode app.js
Visit http://localhost:3000
in your browser and try uploading a file using the form.
That's it! You've successfully implemented file uploads in a Node.js application using Express and Multer. Adjust the code and configurations based on your specific requirements and use cases.