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,32 +35,83 @@
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>

260
script.js
View file

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