How to render BLOB images from database using Flask backend and 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 frontend. My Flask backend retrieves the image successfully, but I’m having trouble showing it properly in the browser.

Backend Flask route:

@app.route('/fetch_image', methods=['POST'])
def fetch_image():
    photo_id = request.form['photo_id']
    # Get image from database
    img_blob = get_image_from_db(photo_id)
    return Response(img_blob, mimetype='image/jpeg')

Frontend HTML form:

<form id="imageForm">
    <label for="photo_id">Photo ID:</label>
    <input type="text" id="photo_id" name="photo_id">
    <button type="submit">Load Image</button>
</form>
<img id="display_image" src="" alt="Loaded image">

JavaScript handling:

document.getElementById('imageForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const photoId = document.getElementById('photo_id').value;
    
    fetch('/fetch_image', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'photo_id=' + encodeURIComponent(photoId)
    })
    .then(response => response.blob())
    .then(imageBlob => {
        const imageUrl = URL.createObjectURL(imageBlob);
        document.getElementById('display_image').src = imageUrl;
    });
});

The image appears in browser dev tools but doesn’t render on the page. What’s the correct way to handle BLOB image data from Flask backend?

add charset=utf-8 to your Flask response headers. also wrap your blob data in BytesIO before returning it - that usually fixes rendering issues. I had the same problem last month and it turned out to be a missing content-length header.

This is likely a BLOB data format or encoding issue. I experienced the same challenge while building a photo gallery app. First, ensure your get_image_from_db() function returns raw binary data without altering the encoding. Additionally, implement error handling in your Flask route to validate the BLOB data before transmission. A solution that proved effective for me was encoding the BLOB in base64 within the Flask route and returning it as JSON. Then, in JavaScript, decode it using the data:image/jpeg;base64, prefix for the image source. This method mitigates binary data corruption during transfer and simplifies debugging when images fail to load.

hmm interesting - getting any console errors? mimetype detection gets tricky with blob data. have you checked if img_blob is actually valid image data before sending? also what database are you using? some systems add extra metadata to blob fields that mess with rendering. try logging the blob size too