Skip to content

Commit

Permalink
fixed delete
Browse files Browse the repository at this point in the history
  • Loading branch information
amgno committed Sep 25, 2024
1 parent 74e0ae0 commit 7ee246d
Show file tree
Hide file tree
Showing 8 changed files with 149 additions and 96 deletions.
4 changes: 0 additions & 4 deletions .todo.txt

This file was deleted.

4 changes: 4 additions & 0 deletions admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,10 @@ <h3>IMG MNG</h3>
<p>Drag and drop images here or click to select files</p>
<input type="file" id="file-input" multiple accept="image/*" style="display: none;">
</div>
<div id="upload-progress-container" style="display: none;">
<progress id="upload-progress" value="0" max="100"></progress>
<span id="upload-progress-text">0%</span>
</div>
</div>
</div>
</div>
Expand Down
125 changes: 71 additions & 54 deletions admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,41 +160,55 @@ function saveProjects() {
});
}

function uploadFiles(index, type) {
const fileInput = document.getElementById(`${index}-${type}-upload`);
const files = fileInput.files;
if (files.length === 0) return;

function uploadFiles(files) {
const formData = new FormData();
formData.append('projectIndex', index);
formData.append('type', type);
formData.append('projectIndex', currentProjectIndex);
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i]);
}

fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showNotification('Files uploaded successfully!');
// Update the project data
if (type === 'images') {
projects[index].images = data.files;
} else if (type === 'pdf') {
projects[index].pdf = data.files[0];
const progressBar = document.getElementById('upload-progress');
const progressText = document.getElementById('upload-progress-text');
const progressContainer = document.getElementById('upload-progress-container');

progressContainer.style.display = 'block';
progressBar.value = 0;
progressText.textContent = '0%';

const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);

xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
progressBar.value = percentComplete;
progressText.textContent = percentComplete.toFixed(2) + '%';
}
};

xhr.onload = function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
if (response.success) {
showNotification('Files uploaded successfully!');
projects[currentProjectIndex].images = projects[currentProjectIndex].images.concat(response.files);
showImageManagement(currentProjectIndex);
} else {
showNotification('Error uploading files: ' + (response.message || 'Unknown error'), true);
}
loadProjects(); // Reload the projects to reflect the changes
} else {
showNotification('Error uploading files: ' + (data.message || 'Unknown error'), true);
showNotification('Error uploading files', true);
}
})
.catch((error) => {
console.error('Error:', error);
progressContainer.style.display = 'none';
};

xhr.onerror = function() {
console.error('Error:', xhr.status);
showNotification('Error uploading files', true);
});
progressContainer.style.display = 'none';
};

xhr.send(formData);
}

function toggleProject(index) {
Expand Down Expand Up @@ -229,36 +243,39 @@ function closeImageManagement() {

function deleteImage(imgIndex) {
if (confirm('Are you sure you want to delete this image?')) {
projects[currentProjectIndex].images.splice(imgIndex, 1);
showImageManagement(currentProjectIndex);
}
}
const project = projects[currentProjectIndex];
const imageToDelete = project.images[imgIndex];

function uploadFiles(files) {
const formData = new FormData();
formData.append('projectIndex', currentProjectIndex);
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i]);
fetch('/delete-image', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
projectIndex: currentProjectIndex,
imagePath: imageToDelete
}),
})
.then(response => response.json())
.then(data => {
if (data.success) {
showNotification('Image deleted successfully!');
// Refresh the projects data
fetch('/projects')
.then(response => response.json())
.then(updatedProjects => {
projects = updatedProjects;
showImageManagement(currentProjectIndex);
});
} else {
showNotification('Error deleting image: ' + (data.message || 'Unknown error'), true);
}
})
.catch((error) => {
console.error('Error:', error);
showNotification('Error deleting image', true);
});
}

fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showNotification('Files uploaded successfully!');
projects[currentProjectIndex].images = projects[currentProjectIndex].images.concat(data.files);
showImageManagement(currentProjectIndex);
} else {
showNotification('Error uploading files: ' + (data.message || 'Unknown error'), true);
}
})
.catch((error) => {
console.error('Error:', error);
showNotification('Error uploading files', true);
});
}

document.addEventListener('DOMContentLoaded', function() {
Expand Down
16 changes: 8 additions & 8 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ services:
environment:
- NODE_ENV=production
- ADMIN_PASSWORD=pass
networks:
- caddy
labels:
caddy: pf.dev.magno.me
caddy.reverse_proxy: "{{upstreams 3000}}"
# networks:
# - caddy
# labels:
# caddy: pf.dev.magno.me
# caddy.reverse_proxy: "{{upstreams 3000}}"


networks:
caddy:
external: true
# networks:
# caddy:
# external: true



Expand Down
8 changes: 4 additions & 4 deletions projects.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ const projects = [
"pdf": "./works/06 - Rolli/document.pdf",
"video": "https://data.088899.xyz/ROLLI-main.mp4",
"images": [
"/works/06 - Rolli di Genova/images/6x3.png",
"/works/06 - Rolli di Genova/images/pass.png",
"/works/06 - Rolli di Genova/images/70x100.png",
"/works/06 - Rolli di Genova/images/IMG_5269.png",
"/works/06 - Rolli di Genova/images/6x3.png",
"/works/06 - Rolli di Genova/images/tote3.png",
"/works/06 - Rolli di Genova/images/mappa7.png",
"/works/06 - Rolli di Genova/images/pass.png",
"/works/06 - Rolli di Genova/images/tote3.png"
"/works/06 - Rolli di Genova/images/IMG_5269.png"
],
"bgcolor": "#590202"
}
Expand Down
12 changes: 12 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

• Lazy load images
• Add a progress bar for uploading images
• Fix the size of buttons on works for mobile view






Done:
• Fix delete function on image manager
76 changes: 50 additions & 26 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,16 @@ function getProjects() {
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const projectIndex = req.body.projectIndex;
const projects = getProjects();
const project = projects[projectIndex];
let dir;
if (file.mimetype === 'application/pdf') {
dir = `./works/${project.number} - ${project.name}`;
} else {
dir = `./works/${project.number} - ${project.name}/images`;
}
fs.mkdirSync(dir, { recursive: true });
cb(null, dir);
const project = getProjects()[projectIndex];
const uploadPath = path.join(__dirname, `works/${project.number} - ${project.name}/images`);
fs.mkdirSync(uploadPath, { recursive: true });
cb(null, uploadPath);
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
limits: {
fileSize: 10 * 1024 * 2024, // 10 MB limit
}
});

Expand All @@ -52,27 +49,14 @@ app.post('/upload', upload.array('files'), (req, res) => {
const projects = getProjects();
const project = projects[projectIndex];
const uploadedFiles = req.files.map(file => {
const relativePath = file.mimetype === 'application/pdf'
? `works/${project.number} - ${project.name}/${file.filename}`
: `works/${project.number} - ${project.name}/images/${file.filename}`;
return { path: relativePath, type: file.mimetype };
return `/works/${project.number} - ${project.name}/images/${file.filename}`;
});

// Append new images to the existing array
if (!projects[projectIndex].images) {
projects[projectIndex].images = [];
}
projects[projectIndex].images = projects[projectIndex].images.concat(
uploadedFiles
.filter(file => file.type.startsWith('image/'))
.map(file => '/' + file.path)
);

// Update the pdf field if a PDF was uploaded
const pdfFile = uploadedFiles.find(file => file.type === 'application/pdf');
if (pdfFile) {
projects[projectIndex].pdf = '/' + pdfFile.path;
}
projects[projectIndex].images = projects[projectIndex].images.concat(uploadedFiles);

// Write the updated projects array back to the file
const updatedData = `const projects = ${JSON.stringify(projects, null, 2)};`;
Expand All @@ -81,7 +65,7 @@ app.post('/upload', upload.array('files'), (req, res) => {
console.error(writeErr);
return res.status(500).json({ success: false, message: 'Error updating projects file' });
}
res.json({ success: true, files: uploadedFiles.map(file => '/' + file.path) });
res.json({ success: true, files: uploadedFiles });
});
});

Expand Down Expand Up @@ -119,4 +103,44 @@ app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});

app.post('/delete-image', (req, res) => {
const { projectIndex, imagePath } = req.body;
const projects = getProjects();

if (projects[projectIndex] && projects[projectIndex].images) {
const imageIndex = projects[projectIndex].images.indexOf(imagePath);
if (imageIndex > -1) {
// Remove the image from the project's images array
projects[projectIndex].images.splice(imageIndex, 1);

// Delete the actual file
fs.unlink(path.join(__dirname, imagePath), (err) => {
if (err) {
console.error('Error deleting file:', err);
return res.status(500).json({ success: false, message: 'Error deleting file' });
}

// Update the projects file
const updatedData = `const projects = ${JSON.stringify(projects, null, 2)};`;
fs.writeFile(path.join(__dirname, 'projects.js'), updatedData, (writeErr) => {
if (writeErr) {
console.error(writeErr);
return res.status(500).json({ success: false, message: 'Error updating projects file' });
}
res.json({ success: true });
});
});
} else {
res.status(404).json({ success: false, message: 'Image not found' });
}
} else {
res.status(404).json({ success: false, message: 'Project or images not found' });
}
});

app.get('/projects', (req, res) => {
const projects = getProjects();
res.json(projects);
});


Binary file removed works/07 - New Project/images/framed_R0000701.JPG
Binary file not shown.

0 comments on commit 7ee246d

Please sign in to comment.