how to make a base64 image downloadable

Using Base64 code to present a image in web pages can be of a lot of benefit, especially when you use Javascript to process a image file and give the result, because this cost no bandwidth and no server-side CPU usage.

However, in some browsers, especially mobile browsers, the Base64 encoded files are not downloadable.

I write this post to keep a record of the way to solve thees problems I ran into recently.

Firstly, make the code downloadable. To do this, we need to some trick on the href attribute inside an a tag. Basically, we just make it look like

<a href="data:application/octet-streamif;base64,{{your_base64_code}}">

Simple as that. But, in some cases, you might need to do the trick by adding the following script:

# img = some_img_tag_object (Jquery)
url = img.attr('src').replace(/^data:image\/[^;]/, 'data:application/octet-stream');
# download_button = some_a_tag_object (Jquery)
download_button.attr('href', download())

This way, you don't have to render your page adding two identical code in it.

Secondly, if you push this button, you'll find the automatically generated file name is some random string or even the first few characters of the Base64 code. The biggest problem is that the extension is usually .bin or no extension, which make your client who works on Windows don't know which software to open the file. Actually, we can fix this by simply add a download attribute to the a tag, like

<a href="data:application/octet-streamif;base64,{{your_base64_code}}" download="image.png">

So, now if you click it, the file name will be the value of the download attribute

If you have any questions, please leave a comment

comments powered by Disqus