How to get base64 string from database media object

Hi @Agobin,

Base64 encoding has a length limit so you may want to use the Media object’s url property in your html instead. To do that, you can just change your client code to the following:

def retrieve_and_show_url_img(self):
    image = app_tables.images.get(number = 1234)[‘media’]
    url = image.url
    html = '<img src="{0}"/>'.format(url)
    self.call_js('printPage', html)

If you do want to use Base64 encoding, I think you’re just missing the closing quote from the src attribute in your img tag.

Try changing your client code to look like this:

import base64
 # ...
 def retrieve_and_show_image(self):
    image = app_tables.images.get(number = 1234)[‘media’]
    encoded_data = base64.b64encode(image.get_bytes())
    html = '<img src="data:svg+xml;base64, {0}"/>'.format(encoded_data)
    self.call_js('printPage', html)

Both functions are working for me with the following JS function:

function printPage(html) {
  var printWindow = window.open('_blank');
  console.log(html);
  printWindow.document.open('text/html');
  printWindow.document.write(html);
} 

Here’s a clone link:

https://anvil.works/build#clone:GQGIJQTKJ7EE4EOB=E7LHZDXK35ULVS6TET3TPORS

1 Like