File uploads in Node.js can be handled using several libraries. One popular choice is express
for building web applications and multer
for handling file uploads. Below is a simple example demonstrating how to set up file uploads using Node.js, Express, and Multer.
First, install the necessary packages:
npm install express multer
Now, create a basic server with file upload functionality:
const express = require('express');
const multer = require('multer');
const path = require('path');
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/'); // Uploads will be stored in the 'uploads' directory
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
},
});
const upload = multer({ storage: storage });
// Serve HTML form for file upload
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Handle file upload
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
res.send('File uploaded successfully.');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Create an index.html
file in the same directory as your server script with the following content:
In this example:
- The
express
framework is used to create a simple web server. -
multer
is used to handle file uploads. The configuration specifies that uploaded files should be stored in theuploads
directory and have a unique filename. - The server provides an HTML form for file uploads at the root ("/") and handles file uploads at the "/upload" endpoint.
- The server listens on port 3000.
Run your Node.js script, navigate to http://localhost:3000 in your browser, and you should see the file upload form. After selecting a file and clicking "Upload," the file will be uploaded to the "uploads" directory. Adjust the code according to your specific requirements and directory structure.