How to render BLOB images from Flask backend in JavaScript frontend

I’m working on a web app where I need to fetch image data stored as BLOB in my database and display it on the webpage. My Flask backend retrieves the image correctly, but I’m having trouble showing it in the frontend.

<!DOCTYPE html>
<html>
<head>
    <title>Image Viewer</title>
</head>
<body>
    <h2>Fetch Image</h2>
    <form id="imageForm">
        <label>Image ID:</label>
        <input type="text" id="img_id" name="img_id">
        <br><br>
        <button type="submit">Load Image</button>
    </form>
    <div id="result">
        <img id="display_img" src="" alt="Loaded image">
    </div>
    
    <script>
        document.getElementById('imageForm').addEventListener('submit', function(e) {
            e.preventDefault();
            var imageId = document.getElementById('img_id').value;
            
            fetch('/loadImage', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({img_id: imageId})
            })
            .then(response => response.blob())
            .then(blob => {
                var imageUrl = URL.createObjectURL(blob);
                document.getElementById('display_img').src = imageUrl;
            });
        });
    </script>
</body>
</html>

My Flask route returns the image like this:

return Response(blob_data, mimetype='image/jpeg')

The image shows up in browser dev tools but not on the actual page. What am I missing here?

hmm thats weird that it shows in dev tools but not visually… are you checking the network tab to see if the response headers look right? also curious - does your blob_data variable actually contain the raw image bytes from your database? sometimes the issue is in how we’re extracting from the BLOB field itself rather than the frontend rendering part.

try adding some error handling to your fetch - maybe the blob conversion is failing silently? also check if your img element has any css that might be hidding it like display:none or weird positioning. i’ve seen cases where the src gets set but the image doesnt render because of styling issues

Check your Flask route’s response headers - you might need to explicitly set CORS headers if your frontend and backend are on different ports. Also verify that your BLOB data is being retrieved properly from the database. Try logging the blob size in your JavaScript after the response to confirm you’re actually receiving data. Another common issue is that some browsers require the image element to have explicit width/height or the parent container needs proper dimensions. You could also try using response.arrayBuffer() instead of response.blob() and then create the blob manually with the correct MIME type to ensure proper handling.