So, I have this project which basically takes an email and buts out the part after @ and makes that into a folder that the person with the email can see from the browser. But the images don’t show up as images, only as image icons and the files name next to them. I’ve tried to rename the files, reupload the files, making img.alt = filename;
to img.alt = photo;
and etc, but I couldn’t find any success. Also, it doesn’t throw any error messages.
The deleting the part after @ was done with this code:
username = req.user.email.split('@')[0]
The server side has this code:
app.get('/uploaded-photos', (req, res) => {
console.log(req.user);
const username = req.user.email.split('@')[0];
fs.readdir(path.join(__dirname, 'uploads', username), (err, files) => {
if (err) {
console.error(`Error reading uploads directory for user ${username}:`, err);
res.status(500).send('Error reading uploads directory');
} else {
res.json(files);
}
});
});
While the client side has this code:
fetch('/uploaded-photos')
.then(response => response.json())
.then(photos => {
const photosContainer = document.getElementById('uploaded-photos');
photos.forEach(photo => {
const img = document.createElement('img');
const filenameParts = photo.split('/');
const filename = filenameParts[filenameParts.length - 1]; //File name
img.src = '/uploads/' + filename; // Path
img.alt = filename;
img.classList.add('preview-image');
photosContainer.appendChild(img);
});
const previewImages = document.querySelectorAll('.preview-image');
previewImages.forEach(img => {
img.addEventListener('click', () => {
alert('A modal could be opened to show in large size');
});
});
})
.catch(error => console.error('Error fetching photos:', error));
And the HTML script for upload.html looks like this:
<script>
fetch('/uploaded-photos')
.then(response => response.json())
.then(photos => {
const photosContainer = document.getElementById('uploaded-photos');
photos.forEach(photo => {
const img = document.createElement('img');
const filenameParts = photo.split('/');
const filename = filenameParts[filenameParts.length - 1]; // Get file name
img.src = './uploads/' + filename; // File path
img.alt = filename;
img.classList.add('preview-image');
photosContainer.appendChild(img);
});
const previewImages = document.querySelectorAll('.preview-image');
previewImages.forEach(img => {
img.addEventListener('click', () => {
alert('Open image in a new tab to view it at the original size.');
});
});
})
.catch(error => console.error('Error fetching photos:', error));
</script>