This commit is contained in:
coast 2025-10-02 10:11:08 +03:30
parent e363f780d7
commit 8ce7ae12b1
3 changed files with 324 additions and 118 deletions

View file

@ -7,6 +7,7 @@
<style> <style>
body { body {
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
overflow-y: scroll;
} }
#file-tree { #file-tree {
margin-top: 20px; margin-top: 20px;
@ -14,6 +15,18 @@
ul { ul {
list-style-type: none; list-style-type: none;
} }
li {
padding: 5px 0;
display: flex;
align-items: center;
}
li button {
margin-left: 10px;
}
.file-info {
flex-grow: 1;
padding-left: 5px;
}
.preview-modal { .preview-modal {
position: fixed; position: fixed;
top: 0; top: 0;
@ -22,36 +35,87 @@
bottom: 0; bottom: 0;
background: rgba(0, 0, 0, 0.8); background: rgba(0, 0, 0, 0.8);
display: flex; display: flex;
flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
z-index: 1000; z-index: 1000;
overflow-y: auto;
padding: 20px;
} }
.preview-content { .preview-content {
background: white; background: white;
padding: 20px; padding: 20px;
border-radius: 5px; border-radius: 5px;
max-width: 90%; max-width: 90%;
max-height: 90%; max-height: 90vh;
overflow: auto; overflow: auto;
position: relative;
} }
img { img {
max-width: 100%; max-width: 100%;
max-height: 400px; max-height: 400px;
display: block;
margin: 0 auto;
}
.upload-item {
display: flex;
align-items: center;
margin-bottom: 5px;
}
.progress-bar {
width: 200px;
height: 20px;
border: 1px solid #ccc;
margin-left: 10px;
overflow: hidden;
border-radius: 3px;
}
.progress-bar-fill {
height: 100%;
width: 0;
background-color: #4CAF50;
transition: width 0.1s;
}
#batch-actions button {
margin-right: 10px;
padding: 8px 15px;
}
.preview-controls {
display: flex;
justify-content: space-between;
width: 100%;
max-width: 90%;
margin-top: 10px;
margin-bottom: 10px;
}
.preview-controls button {
padding: 10px 20px;
font-size: 16px;
} }
</style> </style>
</head> </head>
<body> <body>
<h1>Upload Files</h1> <h1>Upload Files</h1>
<form id="upload-form" action="/upload" method="post" enctype="multipart/form-data"> <form id="upload-form" action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple required> <input type="file" name="files" multiple required id="file-input">
<button type="submit">Upload</button> <button type="submit" id="upload-button">Upload</button>
</form> </form>
<h2>Files to Upload</h2>
<ul id="upload-list">
</ul>
<h2>Directory Structure</h2> <h2>Directory Structure</h2>
<div id="batch-actions">
<button id="select-all">Select All</button>
<button id="batch-download">Download Selected</button>
<button id="batch-delete">Delete Selected</button>
<button id="batch-preview">Preview Selected (Text/Image)</button>
</div>
<div id="file-tree"> <div id="file-tree">
<ul id="file-list"></ul> <ul id="file-list"></ul>
</div> </div>
<script src="script.js"></script> <script src="script.js"></script>
</body> </body>
</html> </html>

358
script.js
View file

@ -1,115 +1,265 @@
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
fetchFiles(); fetchFiles();
document.getElementById('upload-form').addEventListener('submit', handleFileUpload); document.getElementById('upload-form').addEventListener('submit', handleFileUpload);
document.getElementById('file-input').addEventListener('change', updateUploadList);
document.getElementById('select-all').addEventListener('click', handleSelectAll);
document.getElementById('batch-delete').addEventListener('click', handleBatchDelete);
document.getElementById('batch-download').addEventListener('click', handleBatchDownload);
document.getElementById('batch-preview').addEventListener('click', handleBatchPreview);
}); });
function fetchFiles() { function fetchFiles() {
fetch('/files') fetch('/files')
.then(response => response.json()) .then(response => response.json())
.then(files => { .then(files => {
const fileList = document.getElementById('file-list'); const fileList = document.getElementById('file-list');
fileList.innerHTML = ''; fileList.innerHTML = '';
files.forEach(file => { files.forEach(file => {
const li = document.createElement('li'); const li = document.createElement('li');
li.textContent = `${file.name} (Size: ${file.size} bytes, Date: ${new Date(file.date).toLocaleString()})`;
const checkbox = document.createElement('input');
const downloadButton = document.createElement('button'); checkbox.type = 'checkbox';
downloadButton.textContent = 'Download'; checkbox.value = file.name;
downloadButton.onclick = () => { checkbox.dataset.path = `/uploads/${file.name}`;
window.location.href = `/download/${file.name}`; const extension = file.name.split('.').pop().toLowerCase();
}; checkbox.dataset.fileType = extension;
const deleteButton = document.createElement('button'); const fileInfo = document.createElement('span');
deleteButton.textContent = 'Delete'; fileInfo.className = 'file-info';
deleteButton.onclick = () => { fileInfo.textContent = `${file.name} (Size: ${file.size} bytes, Date: ${new Date(file.date).toLocaleString()})`;
fetch(`/delete/${file.name}`, { method: 'DELETE' })
.then(response => { li.appendChild(checkbox);
if (response.ok) { li.appendChild(fileInfo);
li.remove(); fileList.appendChild(li);
alert('File deleted successfully!'); });
} else { })
alert('Error deleting file'); .catch(error => {
} console.error('Error fetching file list:', error);
}); });
}; }
const previewButton = document.createElement('button'); function updateUploadList(event) {
previewButton.textContent = 'Preview'; const fileInput = event.target;
previewButton.onclick = () => { const uploadList = document.getElementById('upload-list');
showPreview(file); uploadList.innerHTML = '';
};
if (fileInput.files.length === 0) return;
li.appendChild(downloadButton);
li.appendChild(deleteButton); for (const file of fileInput.files) {
li.appendChild(previewButton); const li = document.createElement('li');
fileList.appendChild(li); li.className = 'upload-item';
}); li.innerHTML = `
}) <span>${file.name} (Size: ${Math.round(file.size / 1024)} KB)</span>
.catch(error => { <div id="progress-${file.name.replace(/[^a-zA-Z0-9]/g, '-')}" class="progress-bar">
console.error('Error fetching file list:', error); <div class="progress-bar-fill" style="width: 0;"></div>
}); </div>
`;
uploadList.appendChild(li);
}
} }
function handleFileUpload(event) { function handleFileUpload(event) {
event.preventDefault(); event.preventDefault();
const form = event.target; const form = event.target;
const formData = new FormData(form); const formData = new FormData(form);
const fileInput = document.getElementById('file-input');
fetch('/upload', {
method: 'POST', if (fileInput.files.length === 0) {
body: formData alert('Please select files to upload.');
}) return;
.then(response => response.text()) }
.then(message => {
alert(message); const xhr = new XMLHttpRequest();
form.reset();
fetchFiles(); xhr.upload.addEventListener('progress', (e) => {
}) if (e.lengthComputable) {
.catch(error => { const percentComplete = (e.loaded / e.total) * 100;
console.error('Error uploading file:', error); const progressBars = document.querySelectorAll('.progress-bar-fill');
alert('File upload failed!');
}); progressBars.forEach(bar => {
bar.style.width = percentComplete.toFixed(2) + '%';
});
}
}, false);
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
alert(xhr.responseText);
form.reset();
document.getElementById('upload-list').innerHTML = '';
fetchFiles();
} else {
alert('File upload failed! Server responded with status ' + xhr.status);
}
});
xhr.addEventListener('error', () => {
console.error('Error uploading file:', xhr.statusText);
alert('File upload failed!');
});
xhr.open('POST', '/upload');
xhr.send(formData);
}
function getSelectedFiles() {
const selectedCheckboxes = document.querySelectorAll('#file-list input[type="checkbox"]:checked');
return Array.from(selectedCheckboxes).map(checkbox => ({
name: checkbox.value,
path: checkbox.dataset.path,
type: checkbox.dataset.fileType
}));
} }
function showPreview(file) { function handleSelectAll() {
const previewContainer = document.createElement('div'); const checkboxes = document.querySelectorAll('#file-list input[type="checkbox"]');
previewContainer.className = 'preview-modal'; const allChecked = Array.from(checkboxes).every(cb => cb.checked);
const closeButton = document.createElement('button'); checkboxes.forEach(cb => {
closeButton.textContent = 'Close'; cb.checked = !allChecked;
closeButton.onclick = () => { });
document.body.removeChild(previewContainer); }
};
function handleBatchDelete() {
const content = document.createElement('div'); const filesToDelete = getSelectedFiles();
content.className = 'preview-content'; if (filesToDelete.length === 0) {
alert('No files selected for deletion.');
if (file.name.endsWith('.txt')) { return;
const textPreview = document.createElement('iframe'); }
textPreview.src = file.path;
textPreview.style.width = '100%'; if (!confirm(`Are you sure you want to delete ${filesToDelete.length} file(s)?`)) {
textPreview.style.height = '200px'; return;
content.appendChild(textPreview); }
} else if (file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
const imgPreview = document.createElement('img'); const deletePromises = filesToDelete.map(file =>
imgPreview.src = file.path; fetch(`/delete/${file.name}`, { method: 'DELETE' })
imgPreview.onload = () => { .then(response => {
document.body.appendChild(previewContainer); if (response.ok) {
}; return { name: file.name, status: 'Success' };
imgPreview.onerror = () => { } else {
alert('Error loading image preview'); return { name: file.name, status: 'Failed' };
document.body.removeChild(previewContainer); }
}; })
content.appendChild(imgPreview); );
} else {
content.textContent = 'Preview not available for this file type.'; Promise.all(deletePromises)
} .then(results => {
const successfulDeletes = results.filter(r => r.status === 'Success');
previewContainer.appendChild(closeButton); const failedDeletes = results.filter(r => r.status === 'Failed');
previewContainer.appendChild(content);
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) { if (successfulDeletes.length > 0) {
document.body.appendChild(previewContainer); alert(`Successfully deleted ${successfulDeletes.length} file(s).`);
} }
if (failedDeletes.length > 0) {
alert(`Failed to delete ${failedDeletes.length} file(s). Check console for errors.`);
}
fetchFiles();
})
.catch(error => {
console.error('Error during batch deletion:', error);
alert('An error occurred during batch deletion.');
});
}
function handleBatchDownload() {
const filesToDownload = getSelectedFiles();
if (filesToDownload.length === 0) {
alert('No files selected for download.');
return;
}
filesToDownload.forEach(file => {
window.location.href = `/download/${file.name}`;
});
alert(`Initiating download for ${filesToDownload.length} file(s). Check your browser's download manager.`);
}
function handleBatchPreview() {
const selectedFiles = getSelectedFiles();
const previewableFiles = selectedFiles.filter(file =>
file.type === 'txt' || file.type.match(/^(jpg|jpeg|png|gif)$/)
);
if (previewableFiles.length === 0) {
alert('No previewable files (.txt, .jpg, .png, .gif) selected.');
return;
}
showMultiPreview(previewableFiles);
}
function showMultiPreview(files) {
let currentIndex = 0;
const previewContainer = document.createElement('div');
previewContainer.className = 'preview-modal';
const content = document.createElement('div');
content.className = 'preview-content';
const controls = document.createElement('div');
controls.className = 'preview-controls';
const prevButton = document.createElement('button');
prevButton.textContent = 'Previous';
prevButton.onclick = () => {
if (currentIndex > 0) {
currentIndex--;
updatePreviewContent();
}
};
const nextButton = document.createElement('button');
nextButton.textContent = 'Next';
nextButton.onclick = () => {
if (currentIndex < files.length - 1) {
currentIndex++;
updatePreviewContent();
}
};
const closeButton = document.createElement('button');
closeButton.textContent = 'Close Preview';
closeButton.onclick = () => {
document.body.removeChild(previewContainer);
};
controls.appendChild(prevButton);
controls.appendChild(closeButton);
controls.appendChild(nextButton);
const updatePreviewContent = () => {
content.innerHTML = '';
const file = files[currentIndex];
prevButton.disabled = currentIndex === 0;
nextButton.disabled = currentIndex === files.length - 1;
const counter = document.createElement('p');
counter.textContent = `File ${currentIndex + 1} of ${files.length}: ${file.name}`;
content.appendChild(counter);
if (file.type === 'txt') {
const textPreview = document.createElement('iframe');
textPreview.src = file.path;
textPreview.style.width = '100%';
textPreview.style.height = '400px';
content.appendChild(textPreview);
} else if (file.type.match(/^(jpg|jpeg|png|gif)$/)) {
const imgPreview = document.createElement('img');
imgPreview.src = file.path;
content.appendChild(imgPreview);
} else {
content.textContent = `Preview not available for this file type: ${file.name}.`;
}
};
previewContainer.appendChild(controls);
previewContainer.appendChild(content);
document.body.appendChild(previewContainer);
updatePreviewContent();
} }

View file

@ -5,7 +5,6 @@ const fs = require('fs');
const app = express(); const app = express();
// configure storage for uploaded files
const storage = multer.diskStorage({ const storage = multer.diskStorage({
destination: (req, file, cb) => { destination: (req, file, cb) => {
cb(null, 'uploads/'); cb(null, 'uploads/');
@ -18,10 +17,8 @@ const storage = multer.diskStorage({
const upload = multer({ storage: storage }); const upload = multer({ storage: storage });
// serve static files
app.use(express.static(__dirname)); app.use(express.static(__dirname));
// upload files
app.post('/upload', upload.array('files'), (req, res) => { app.post('/upload', upload.array('files'), (req, res) => {
if (!req.files || req.files.length === 0) { if (!req.files || req.files.length === 0) {
return res.status(400).send('No files were uploaded.'); return res.status(400).send('No files were uploaded.');
@ -29,7 +26,6 @@ app.post('/upload', upload.array('files'), (req, res) => {
res.send(`Successfully uploaded ${req.files.length} file(s)!`); res.send(`Successfully uploaded ${req.files.length} file(s)!`);
}); });
// get list of uploaded files
app.get('/files', (req, res) => { app.get('/files', (req, res) => {
const directoryPath = path.join(__dirname, 'uploads'); const directoryPath = path.join(__dirname, 'uploads');
fs.readdir(directoryPath, (err, files) => { fs.readdir(directoryPath, (err, files) => {
@ -59,7 +55,6 @@ app.get('/files', (req, res) => {
}); });
}); });
// serve a specific file
app.get('/uploads/:filename', (req, res) => { app.get('/uploads/:filename', (req, res) => {
const filePath = path.join(__dirname, 'uploads', req.params.filename); const filePath = path.join(__dirname, 'uploads', req.params.filename);
res.sendFile(filePath, err => { res.sendFile(filePath, err => {
@ -69,7 +64,6 @@ app.get('/uploads/:filename', (req, res) => {
}); });
}); });
// download a specific file
app.get('/download/:filename', (req, res) => { app.get('/download/:filename', (req, res) => {
const filePath = path.join(__dirname, 'uploads', req.params.filename); const filePath = path.join(__dirname, 'uploads', req.params.filename);
res.download(filePath, err => { res.download(filePath, err => {
@ -79,7 +73,6 @@ app.get('/download/:filename', (req, res) => {
}); });
}); });
// delete a specific file
app.delete('/delete/:filename', (req, res) => { app.delete('/delete/:filename', (req, res) => {
const filePath = path.join(__dirname, 'uploads', req.params.filename); const filePath = path.join(__dirname, 'uploads', req.params.filename);
fs.unlink(filePath, err => { fs.unlink(filePath, err => {
@ -90,7 +83,6 @@ app.delete('/delete/:filename', (req, res) => {
}); });
}); });
// start the server
app.listen(3000, () => { app.listen(3000, () => {
console.log('Server is running on http://localhost:3000'); console.log('[*] Server is running on http://localhost:3000');
}); });