Below is an example of a simple file management web application built with Node.js, Express, and Multer. In this sample, you’ll be able to upload files, view a list of uploaded files, download them, and delete files. This is a starting point inspired by solutions like Infrakit. Note: This is a basic example. In a production environment you must add proper security measures (e.g. authentication, file type and size checking, protection from path traversal attacks, etc.).
Below are the steps and code samples to get you started.
1. Setup Your Project
Create a new folder for your project (e.g., file-manager) and initialize a new Node.js project:
mkdir file-manager
cd file-manager
npm init -y
Then install the required dependencies:
npm install express multer ejs
2. Project Structure
Your folder structure could be similar to the following:
file-manager/
├── app.js
├── package.json
├── views/
│ └── index.ejs
└── uploads/ <-- This folder will store the uploaded files
Make sure to create an empty uploads directory:
mkdir uploads
3. Code
app.js
This file sets up your Express server, configures Multer for file uploads, and exposes endpoints to list, upload, download, and delete files.
const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Set view engine to EJS
app.set('view engine', 'ejs');
// Set static folder to serve uploaded files if needed
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(express.urlencoded({ extended: true }));
// Configure Multer storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
// Keep original file name. In a production app, consider generating a unique name.
cb(null, file.originalname);
}
});
const upload = multer({ storage: storage });
// Route: GET "/" - Home page with file list and upload form
app.get('/', (req, res) => {
fs.readdir(path.join(__dirname, 'uploads'), (err, files) => {
if (err) {
console.error(err);
return res.render('index', { files: [] });
}
res.render('index', { files });
});
});
// Route: POST "/upload" - Handle file upload
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
res.redirect('/');
});
// Route: GET "/download/:filename" - Download file
app.get('/download/:filename', (req, res) => {
const file = path.join(__dirname, 'uploads', req.params.filename);
res.download(file, err => {
if (err) {
console.error(err);
res.status(404).send('File not found');
}
});
});
// Route: POST "/delete" - Delete file
app.post('/delete', (req, res) => {
const filename = req.body.filename;
const filePath = path.join(__dirname, 'uploads', filename);
fs.unlink(filePath, err => {
if (err) {
console.error(err);
return res.status(500).send('Failed to delete file.');
}
res.redirect('/');
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
views/index.ejs
This EJS template displays an upload form and a list of uploaded files with options to download or delete them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Manager</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.file-list { margin-top: 20px; }
.file-item { margin-bottom: 10px; }
form { display: inline; }
</style>
</head>
<body>
<h1>File Manager</h1>
<!-- Upload Form -->
<h2>Upload a File</h2>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
<!-- File List -->
<div class="file-list">
<h2>Uploaded Files</h2>
<% if (files.length === 0) { %>
<p>No files uploaded yet.</p>
<% } else { %>
<ul>
<% files.forEach(function(file){ %>
<li class="file-item">
<%= file %>
(<a href="/download/<%= encodeURIComponent(file) %>">Download</a>)
<form action="/delete" method="POST" style="display:inline;">
<input type="hidden" name="filename" value="<%= file %>">
<button type="submit">Delete</button>
</form>
</li>
<% }); %>
</ul>
<% } %>
</div>
</body>
</html>
4. Running the Application
-
Start your server by running:
node app.js
-
Open your browser and navigate to http://localhost:3000.
-
You can now upload files using the form, see a list of uploaded files, download any file by clicking its link, or delete files using the delete button.
Final Notes
- Security: This is a minimal example. Remember to add robust error handling, input validations, authentication, logging, and other security measures in a real-world application.
- File Names: In production, you might need to sanitize file names or generate unique file names if you expect many collisions.
- Scalability: Depending on your needs, you may want to add features like user accounts, file metadata management, and/or integration with cloud storage.
This example should give you a good starting point for building a file management website inspired by Infrakit. Feel free to expand and customize it to suit your needs!