Download data url file

Mikee picture Mikee · Oct 12, 2010 · Viewed 375k times · Source

I'm playing with the idea of making a completely JavaScript-based zip/unzip utility that anyone can access from a browser. They can just drag their zip directly into the browser and it'll let them download all the files within. They can also create new zip files by dragging individual files in.

I know it'd be better to do it serverside, but this project is just for a bit of fun.

Dragging files into the browser should be easy enough if I take advantage of the various methods available. (Gmail style)

Encoding/decoding should hopefully be fine. I've seen some as3 zip libraries so I'm sure I should be fine with that.

My issue is downloading the files at the end.

window.location = 'data:jpg/image;base64,/9j/4AAQSkZJR....' 

this works fine in firefox but not in chrome.

I can embed the files as images just fine in chrome using <img src="data:jpg/image;ba.." />, but the files won't necessarily be images. They could be any format.

Can anyone think of another solution or some kind of workaround?

Answer

owencm picture owencm · Apr 5, 2013

If you also want to give a suggested name to the file (instead of the default 'download') you can use the following in Chrome, Firefox and some IE versions:

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}

And the following example shows it's use:

downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");