How to render a backend-retrieved image on the frontend using Flask and JavaScript?

I’m working on a web app that needs to fetch and display images stored as BLOB files in a SQL database. The backend is built with Flask, and the frontend uses JavaScript. I’ve set up a form to submit requests and JavaScript to handle the response, but I’m struggling to get the image to show up on the web page.

Here’s a simplified version of my current setup:

<form id="imageForm">
  <input type="text" id="imageId">
  <button type="submit">Get Image</button>
</form>
<img id="displayImage" src="">

<script>
document.getElementById('imageForm').onsubmit = function(e) {
  e.preventDefault();
  let id = document.getElementById('imageId').value;
  fetch('/getImage', {
    method: 'POST',
    body: new URLSearchParams({ 'image_id': id })
  })
  .then(response => response.blob())
  .then(blob => {
    let imageUrl = URL.createObjectURL(blob);
    document.getElementById('displayImage').src = imageUrl;
  });
};
</script>

On the backend, I’m sending the image data like this:

return send_file(io.BytesIO(image_data), mimetype='image/png')

The image data seems to be coming through (I can see it in the network tab), but it’s not showing up on the page. Any ideas on what I might be doing wrong or how to troubleshoot this?

hey there! have u checked if the image is actually loading in the network tab? sometimes the issue is with how the blob’s handled. try console.logging the blob data to see what’s up. also, make sure ur img element exists when u set its src. just some ideas to help ya troubleshoot!

Have you checked if the image data is being properly encoded before sending it from the backend? One common issue is that binary data can get corrupted during transmission. Try using base64 encoding on your image data before sending it:

import base64

# In your Flask route
image_base64 = base64.b64encode(image_data).decode('utf-8')
return jsonify({'image': image_base64})

Then on the frontend, decode it before creating the blob:

.then(response => response.json())
.then(data => {
  let binary = atob(data.image);
  let array = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    array[i] = binary.charCodeAt(i);
  }
  return new Blob([array], {type: 'image/png'});
})
.then(blob => {
  let imageUrl = URL.createObjectURL(blob);
  document.getElementById('displayImage').src = imageUrl;
});

This approach ensures the image data remains intact during transmission and might resolve your display issues.

hey there! have u tried checking the network tab to see if the image data is actually being received? sometimes the issue can be with how the blob is handled. maybe try console.logging the blob data to see whats going on? also, double-check that ur img element is actually present in the DOM when u try to set its src. just some ideas to help troubleshoot!