Download data url file

By | December 28, 2017
Questions:

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 find in chrome using <img src="data:jpg/image;ba.." />, but the files wont necessarily be images. They could be any format.

Can anyone think of another solution or some kind of work around?

Answers:

Ideas:

  • Try a <a href="data:...." target="_blank"> (Untested)

  • Use downloadify instead of data URLs (would work for IE as well)

Questions:
Answers:

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");

Questions:
Answers:

Want to share my experience and help someone stuck on the downloads not working in Firefox and updated answer to 2014.
The below snippet will work in both firefox and chrome and it will accept a filename:

  // Construct the <a> element
  var link = document.createElement("a");
  link.download = thefilename;
  // Construct the uri
  var uri = 'data:text/csv;charset=utf-8;base64,' + someb64data
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  // Cleanup the DOM
  document.body.removeChild(link);
  delete link;

Questions:
Answers:

There are several solutions but they depend on HTML5 and haven’t been implemented completely in some browsers yet. Examples below were tested in Chrome and Firefox (partly works).

  1. Canvas example with save to file support. Just set your document.location.href to the data URI.
  2. Anchor download example. It uses <a href="your-data-uri" download="filename.txt"> to specify file name.
Questions:
Answers:

Here is a pure javascript solution I tested working in firefox and chrome but not in iexplorer:

function downloadDataUrlFromJavascript(filename, dataUrl) {

    // Construct the a element
    var link = document.createElement("a");
    link.download = filename;
    link.target = "_blank";

    // Construct the uri
    link.href = dataUrl;
    document.body.appendChild(link);
    link.click();

    // Cleanup the DOM
    document.body.removeChild(link);
    delete link;
}

Cross browser solutions found until now:

downloadify -> requires flash

databounce -> tested in iexplorer 10 and 11 doesn’t work for me, requires a servlet and some customization (incorrectly detect navigator I had to set iexplorer in compatibility mode to test, default charset in servlet, javascript options object with correct servlet path for absolute paths…) for not iexplorer it opens the file in the same window.

download.js http://danml.com/download.html another library similar but not tested, claims to be pure javascript, not requiring servlet nor flash but only works on iexplorer 10 and 11

Questions:
Answers:

Combining answers from @owencm and @Chazt3n, this function will allow download of text from IE11, Firefox, and Chrome. (Sorry, I don’t have access to Safari or Opera, but please add a comment if you try and it works.)

initiate_user_download = function(file_name, mime_type, text) {
    // Anything but IE works here
    if (undefined === window.navigator.msSaveOrOpenBlob) {
        var e = document.createElement('a');
        var href = 'data:' + mime_type + ';charset=utf-8,' + encodeURIComponent(text);
        e.setAttribute('href', href);
        e.setAttribute('download', file_name);
        document.body.appendChild(e);
        e.click();
        document.body.removeChild(e);
    }
    // IE-specific code
    else {
        var charCodeArr = new Array(text.length);
        for (var i = 0; i < text.length; ++i) {
            var charCode = text.charCodeAt(i);
            charCodeArr[i] = charCode;
        }
        var blob = new Blob([new Uint8Array(charCodeArr)], {type: mime_type});
        window.navigator.msSaveOrOpenBlob(blob, file_name);
    }
}

// Example:
initiate_user_download('data.csv', 'text/csv', 'Sample,Data,Here\n1,2,3\n');

Questions:
Answers:
// ========================================
// ==          Download dataURL          ==
// = Downloads a dataURL in a local file ==
// = Include this header if you use it!  ==
// =               Namaste!              ==
// ==        By zibri@zibri.org          ==
// ========================================

function download(dataurl, filename) {
  var a = document.createElement("a");
  a.href = dataurl;
  a.setAttribute("download", filename);
  var b = document.createEvent("MouseEvents");
  b.initEvent("click", false, true);
  a.dispatchEvent(b);
  return false;
}

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

Questions:
Answers:

One may also initiate data URL downloads via JavaScript. See https://stackoverflow.com/a/13696029/271577 for such a solution (along with text link examples).

Questions:
Answers:

Your problem essentially boils down to “not all browsers will support this”.

You could try a workaround and serve the unzipped files from a Flash object, but then you’d lose the JS-only purity (anyway, I’m not sure whether you currently can “drag files into browser” without some sort of Flash workaround – is that a HTML5 feature maybe?)

Questions:
Answers:

For anyone having issues in IE:

Please upvote the answer here by Yetti:
saving canvas locally in IE

dataURItoBlob = function(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/png'});
}

var blob = dataURItoBlob(uri);
window.navigator.msSaveOrOpenBlob(blob, "my-image.png");

Leave a Reply

Your email address will not be published. Required fields are marked *