I need to create an HTML gallery dynamically without saving the files to disk. I need to retrieve the data from single RAR files or split RAR files (e.g., rar, r01, r02, r03, and so on).
I’m open to any solution, whether using Blob or Buffer, as long as I can achieve this goal.
I am providing two RAR files as examples here. Please note that I will be working with large files.
Sever:
const express = require('express');
const path = require('path');
const fs = require('fs');
const { Unrar } = require('unrar-js');
const app = express();
const PORT = 3000;
// Set up static directory to serve HTML and JS files
app.use(express.static(path.join(__dirname, 'public')));
const rarFilePath = path.join(__dirname, 'example_rar_5.rar');
// Route to get the list of images
app.get('/images', async (req, res) => {
try {
const rarBuffer = fs.readFileSync(rarFilePath);
const unrar = new Unrar(rarBuffer);
const entries = unrar.list();
const imageEntries = entries.filter(entry => /.(png|jpg|jpeg|gif)$/.test(entry.name));
const imageFilenames = imageEntries.map(entry => entry.name);
res.json(imageFilenames);
} catch (error) {
console.error('Error listing images:', error);
res.status(500).send('Error processing the RAR file');
}
});
// Route to serve images as Blob
app.get('/images/:filename', async (req, res) => {
const filename = req.params.filename;
try {
const rarBuffer = fs.readFileSync(rarFilePath);
const unrar = new Unrar(rarBuffer);
const entries = unrar.list();
const entry = entries.find(e => e.name === filename);
if (entry) {
const extracted = unrar.extract(entry);
res.set('Content-Type', entry.name.endsWith('.png') ? 'image/png' : 'image/jpeg');
res.send(extracted[0].fileData); // Send the image as blob
} else {
res.status(404).send('File not found');
}
} catch (error) {
console.error('Error extracting image:', error);
res.status(500).send('Error processing the RAR file');
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RAR Image Viewer</title>
</head>
<body>
<h1>Images from RAR</h1>
<div id="image-container"></div>
<script>
const imageContainer = document.getElementById('image-container');
// Make a request to get the list of images
fetch('/images')
.then(response => response.json())
.then(imageFilenames => {
imageFilenames.forEach(filename => {
fetch(`/images/${filename}`)
.then(response => response.blob())
.then(blob => {
const img = document.createElement('img');
img.src = URL.createObjectURL(blob); // Create a URL for the blob
img.alt = filename;
img.style.width = '200px';
img.style.margin = '10px';
imageContainer.appendChild(img);
})
.catch(error => {
console.error('Error loading the image:', error);
});
});
})
.catch(error => {
console.error('Error loading images:', error);
});
</script>
</body>
</html>