Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rjcorwin/6393543 to your computer and use it in GitHub Desktop.

Select an option

Save rjcorwin/6393543 to your computer and use it in GitHub Desktop.

Creating files in the browser with #javascript.md

Interesting plugin using some abandonded saveAs() spec

Build a file

The Blob docs for FF -> https://developer.mozilla.org/en-US/docs/Web/API/Blob?redirectlocale=en-US&redirectslug=DOM%2FBlob

Create a file and put it in a download link... window.URL = window.URL || window.webkitURL; var blob = new Blob(['body { color: red; }'], {type: 'text/css'}); var link = document.createElement('a'); link.innerHTML = 'To download, right click and select "Save As"' link.href = window.URL.createObjectURL(blob); document.body.appendChild(link); from http://updates.html5rocks.com/2012/06/Don-t-Build-Blobs-Construct-Them

Basic, but does not give you ability to name file.

The following will download the blob file with a specific name! Yay! But this does not work in FF :(... window.URL = window.URL || window.webkitURL var blob = new Blob(['body { color: red; }'], {type: 'text/css'}) var link = document.createElement('a') link.innerHTML = 'Click to download style.css.' link.href = window.URL.createObjectURL(blob) link.download = 'style.css' document.body.appendChild(link)

Interesting... Shows you the file at the ObjectURL. window.URL = window.URL || window.webkitURL var blob = new Blob(['body { color: red; }'], {type: 'text/css'}) document.location = window.URL.createObjectURL(blob)

...

document.location = 'data:Application/octet-stream,' + encodeURIComponent(dataToDownload);

from http://blogs.adobe.com/cantrell/archives/2012/01/how-to-download-data-as-a-file-from-javascript.html

The beginning of being able to name a blob download, the download attribute...

"The real benefit of a[download] will be when working with blob: URLs and filesystem: URLs URLs. It'll give users a way to download content created/modified within your app." http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download

Led to an example in the adobe blog comments...

window.URL = window.URL || window.webkitURL;

document.getElementById(‘download’).onclick = function () {
  var a = document.createElement(‘a’);
  var blob = new Blob([dataToDownload], {‘type’:'application\/octet-stream’});
  a.href = window.URL.createObjectURL(blob);
  a.download = ‘filename.ext’;
  a.click();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment