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?