How to Download a File in HTML
Downloading an Image
To allow download of an image in the browser, we can use the anchor
<a> link tag.
<a href="/images/kitten.jpg" download> <img src="/images/kitten.jpg" alt="kitten"> </a>HTML
Set the href attribute to point to the image. The "download" attribute enables downloading when link is clicked.
Downloading the HTML5 Canvas
To download an image drawn on the HTML5 canvas, we should extract the canvas image data in a format that can be fed into the anchor tag.
The dataURL is a format designed to enable inclusion of ASCII string encoded data, in-line on web pages.
The dataURL (abbreviated):
Note the data string is prefixed with
data:image/jpeg;base64. This indicates that the data is a JPEG image in base64 binary format.
The dataURL can be used as the href value of the anchor tag.
The app below will
download a jpeg file from the image drawn to canvas. The images displayed, the kitten
and the pink text, will be combined using the canvas
The composit image will appear in the areas indicated by the RESULT text, and automatically download. Click the link if you want to examine the app code (view the HTML source).
Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.