How to get base64 string from database media object

I noticed in anvil that when I upload an image as the source of an image element from the toolbox, the source gets encoded and converted to a jpeg base64 string.

I tried getting the base64 string of an image from the database and displaying it in my html page but the image wasn’t created. Here is my code sample.

#Client code
import base64

#Any svg image from my database
image = app_tables.images.get(number = 1234)[‘media’]
encoded_data = base64.b64encode(image.get_bytes())

html = “”"<img src=“data:image/svg+xml;base64, {0} > “””.format(encoded_data)
self.call_js(‘printPage’, html)

This is my javascript function:


<script>

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

</script>

I don’t know what could be wrong. Any help on how to fix this would be much appreciated. Thank you.

1 Like

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

Thanks very much @bridget, this works.

A post was split to a new topic: Time concerns when using base64 encoding