I’m trying to upload an Excel file in my Node.js application using Express, Multer, and the XLSX library. I’ve put together the following setup, but I want to ensure I’m doing it correctly and efficiently. Here is my code:
server.js
const multer = require(‘multer’);
const xlsx = require(‘xlsx’);
const path = require(‘path’);
const fs = require(‘fs’);
const app = express();
// Serve the HTML file for the upload form
app.get(‘/’, (req, res) => {
res.sendFile(path.join(__dirname, ‘index.html’));
});
// Multer configuration
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, ‘./uploads’); // Uploads directory
},
filename: function (req, file, cb) {
cb(null, file.fieldname + ‘-‘ + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
fileFilter: function (req, file, cb) {
const ext = path.extname(file.originalname);
if (ext !== ‘.xlsx’ && ext !== ‘.xls’) {
return cb(new Error(‘Only Excel files are allowed’));
}
cb(null, true);
}
});
// Route to handle file upload
app.post(‘/upload’, upload.single(‘excel’), (req, res) => {
try {
if (!req.file) {
return res.status(400).send(‘Please upload an Excel file’);
}
// Process uploaded file
const filePath = req.file.path;
const workbook = xlsx.readFile(filePath);
const sheetName = workbook.SheetNames[0]; // Assuming it’s the first sheet
// Reading the first sheet
const worksheet = workbook.Sheets[sheetName];
const data = xlsx.utils.sheet_to_json(worksheet);
console.log(data);
// Redirect to the main page
res.redirect(‘/’);
} catch (error) {
console.error(error);
res.status(500).send(‘Error processing file’);
}
});
index.html
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Upload Excel</title>
</head>
<body>
<h1>Upload Excel File</h1>
<form action=”/upload” method=”post” enctype=”multipart/form-data”>
<input type=”file” name=”excel” accept=”.xls, .xlsx” required>
<button type=”submit”>Upload</button>
</form>
</body>
</html>
Explanation
Express: Handles HTTP requests and serves static files (index.html).
Multer: Middleware for handling multipart/form-data, used here for file uploads.
XLSX: Library for parsing Excel files.
Path and FS: Node.js modules for handling file paths and system operations.
How It Works:
HTML Form: Provides a form for users to upload Excel files.
Multer Configuration: Sets up Multer to save uploaded files in the ./uploads directory and filter for .xlsx and .xls file types.
File Upload Route: Handles the file upload, reads the Excel file using xlsx.readFile, extracts data from the first sheet, and logs the data to the console.
Questions:
Is this the best way to handle Excel file uploads and processing in Node.js?
Are there any improvements or best practices I should consider for error handling and security?
Any advice or suggestions would be greatly appreciated!