In Express.js, handling file uploads can be achieved using middleware such as multer.
Multer is a popular middleware for handling multipart/form-data, which is used for file uploads.
Set up file uploader using Multer in an Express.js application:
npm install express multer
const multer = require('multer'); const express = require('express'); const path = require('path'); const app = express(); const port = process.env.PORT || 3000; // Set up storage using Multer const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/'); // Specify the directory where uploaded files will be stored }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); }, }); // Create a Multer instance with the storage configuration const upload = multer({ storage: storage }); // Set up a route to handle file uploads app.post('/upload', upload.single('file'), (req, res) => { // 'file' is the name attribute of the file input field in your HTML form // req.file contains information about the uploaded file res.send('File uploaded successfully!'); });
const express = require('express'); const multer = require('multer'); const path = require('path'); const app = express(); const port = process.env.PORT || 3000; // Set up storage using Multer const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/'); // Specify the directory where uploaded files will be stored }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); }, }); // Create a Multer instance with the storage configuration const upload = multer({ storage: storage }); // Set up a route to handle file uploads app.post('/upload', upload.single('file'), (req, res) => { // 'file' is the name attribute of the file input field in your HTML form // req.file contains information about the uploaded file res.send('File uploaded successfully!'); }); // Serve a simple HTML form for testing app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'index.html')); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });
<!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>
Now, when we navigate to http://localhost:3000, we should see a simple form that allows us to select and upload a file.
The uploaded file will be stored in the uploads directory, and the server will respond with "File uploaded successfully!" once the upload is complete.