@lottie
To retrieve a blob image from MySQL and display it in a React.js component, you can follow these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
app.get('/api/images/:id', (req, res) => { const { id } = req.params; // Use your MySQL library of choice to query the image data from the database based on the id const sql = 'SELECT image FROM images WHERE id = ?'; db.query(sql, [id], (error, results) => { if (error) { console.error(error); res.status(500).json({ error: 'Failed to fetch the image' }); } else if (results.length > 0) { const image = results[0].image; // Send the image data as a response res.contentType('image/jpeg'); // Set the appropriate content-type based on your image type res.send(image); } else { res.status(404).json({ error: 'Image not found' }); } }); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import React, { useEffect, useState } from 'react'; const ImageComponent = () => { const [imageUrl, setImageUrl] = useState(''); useEffect(() => { const fetchImage = async () => { try { const response = await fetch('/api/images/1'); // Replace "1" with the actual image id const blob = await response.blob(); const url = URL.createObjectURL(blob); setImageUrl(url); } catch (error) { console.error(error); } }; fetchImage(); }, []); return ( <div> <img src={imageUrl} alt="Image" /> </div> ); }; export default ImageComponent; |
By following these steps, you should be able to fetch the blob image from MySQL and display it in your React.js component.