Question
How can I send a Base64 encoded image string as a response from an Express.js server?
Asked by: USER7634
85 Viewed
85 Answers
Answer (85)
Sending a Base64 encoded image from an Express.js server is a common pattern for embedding images directly into JSON responses or rendering them in web pages.
Here's how you can set up an Express route to read an image, convert it to Base64, and send it as a JSON response:
```javascript
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const app = express();
const PORT = 3000;
// Helper function to convert image to Base64 with data URI
async function getImageBase64(imageFileName) {
const imagePath = path.join(__dirname, 'public/images', imageFileName); // Assuming images are in a 'public/images' folder
try {
const imageData = await fs.readFile(imagePath);
const base64Image = imageData.toString('base64');
const mimeType = path.extname(imagePath).slice(1).toLowerCase();
return `data:image/${mimeType};base64,${base64Image}`;
} catch (error) {
console.error(`Failed to read or convert image ${imageFileName}:`, error);
return null;
}
}
// Route to get a Base64 image by filename
app.get('/api/image/:filename', async (req, res) => {
const filename = req.params.filename;
if (!filename) {
return res.status(400).json({ message: 'Filename is required.' });
}
try {
const base64String = await getImageBase64(filename);
if (base64String) {
res.json({
filename: filename,
base64: base64String
});
} else {
res.status(404).json({ message: 'Image not found or could not be processed.' });
}
} catch (error) {
console.error('Error in /api/image/:filename route:', error);
res.status(500).json({ message: 'Internal server error.' });
}
});
// Serve static files (optional, for direct image access)
app.use('/static', express.static(path.join(__dirname, 'public')));
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Test with: http://localhost:${PORT}/api/image/sample.png`);
});
```
**To make this runnable:**
1. Create a directory named `public` at the root of your project, and inside it, create another directory named `images`.
2. Place a sample image (e.g., `sample.png`) inside the `public/images` directory.
3. Run `node your_server_script.js`.
4. Access `http://localhost:3000/api/image/sample.png` in your browser or a tool like Postman to see the JSON response containing the Base64 string.