Skip to content

Instantly share code, notes, and snippets.

@panzi
Created November 1, 2012 04:58
Show Gist options
  • Save panzi/3991938 to your computer and use it in GitHub Desktop.
Save panzi/3991938 to your computer and use it in GitHub Desktop.
Save/download data generated in JavaScript (1)
<!DOCTYPE html>
<html>
<head>
<title>Save Generated Data</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1"/>
<script type="text/javascript">
// <![CDATA[
var showSave;
var DownloadAttributeSupport = 'download' in document.createElement('a');
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
navigator.saveBlob = navigator.saveBlob || navigator.msSaveBlob || navigator.mozSaveBlob || navigator.webkitSaveBlob;
window.saveAs = window.saveAs || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs;
var BrowserSupportedMimeTypes = {
 "image/jpeg": true,
 "image/png": true,
 "image/gif": true,
 "image/svg+xml": true,
 "image/bmp": true,
 "image/x-windows-bmp": true,
 "image/webp": true,
 "audio/wav": true,
 "audio/mpeg": true,
 "audio/webm": true,
 "audio/ogg": true,
 "video/mpeg": true,
 "video/webm": true,
 "video/ogg": true,
 "text/plain": true,
 "text/html": true,
 "text/xml": true,
 "application/xhtml+xml": true,
 "application/json": true
};
if (BlobBuilder && navigator.saveBlob) {
 showSave = function (data, name, mimetype) {
  var builder = new BlobBuilder();
  builder.append(data);
  var blob = builder.getBlob(mimetype||"application/octet-stream");
  if (!name) name = "Download.bin";
  if (window.saveAs) {
   window.saveAs(blob, name);
  }
  else {
   navigator.saveBlob(blob, name);
  }
 };
}
else if (BlobBuilder && URL) {
 showSave = function (data, name, mimetype) {
  var blob, url, builder = new BlobBuilder();
  builder.append(data);
  if (!mimetype) mimetype = "application/octet-stream";
  if (DownloadAttributeSupport) {
blob = builder.getBlob(mimetype);
url = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href",url);
link.setAttribute("download",name||"Download.bin");
var event = document.createEvent('MouseEvents');
 event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
 link.dispatchEvent(event);
}
else {
@panzi
Copy link
Author

panzi commented Nov 1, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment