To upload multiple files using Node.js, you can use the express
framework along with the multer
middleware. Here's a step-by-step guide:
-
Install necessary packages:
Install
express and multer
using npm:npm install express multer
-
Create your Node.js application:
Create a file (e.g.,
app.js
) and set up your basic Express application: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: (req, file, cb) => { cb(null, 'uploads/'); // The directory where uploaded files will be stored }, filename: (req, file, cb) => { const fileName = `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`; cb(null, fileName); }, }); const upload = multer({ storage: storage }); // Serve static files (optional) app.use(express.static('public')); // Set up a route to handle file uploads app.post('/upload', upload.array('files', 5), (req, res) => { // 'files' is the name attribute in the HTML form for the file input // req.files contains an array of files res.json({ message: 'Files uploaded successfully!', files: req.files }); }); // Start the server app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
-
Create an HTML form for file uploads:
Create an HTML file (e.g.,
index.html
) with a form for file uploads:<!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="files" multiple> <button type="submit">Upload</button> </form> </body> </html>
-
Run your Node.js application:
node app.js
Visit
http://localhost:3000/
in your browser, select multiple files using the file input, and click the "Upload" button. The server will handle the file uploads, and the response will contain information about the uploaded files.
Remember to customize the file storage destination, naming strategy, and other options based on your application's requirements. Additionally, handle errors and edge cases appropriately in a production environment.