Creating downloadable files in HTML

Hi guys.
Continuing the conversation from here, is there a way to create downloadable files in HTML, i mean files that can be shown in the browser downloads?

Yes! First you need to obtain an URL to your downloaded file. If it’s something you just generated, like a screenshot, make sure it’s a data URL (like this: data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7).

In JS (writing this from memory, so might not be 100% accurate):

  1. Create an <a> tag with something like const el = document.createElement('a')
  2. Set el.href = yourUrl
  3. Set el.download = 'yourfilename.gif'. This might not work on all browsers, though.
  4. Add it to <body>: document.body.append(el)
  5. Click it: el.click(). This might not work if not done from a user-generated JS event, like onclick. Defold’s on_input doesn’t count. You’ll need to find a way to attach it to a JS event.
  6. Remove it from the DOM: el.remove()
5 Likes