Skip to content

Instantly share code, notes, and snippets.

@lili21
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lili21/13f6b88d58920691f8e4 to your computer and use it in GitHub Desktop.
Save lili21/13f6b88d58920691f8e4 to your computer and use it in GitHub Desktop.
save as (front end file saver)
;(function(self) {
'use strict';
/**
* 将base64数据转成Blob对象,
* @param {string} base64 base64字符串
* @param {string} type mime type
* @param {number} size slice size
* @return {object} Blob对象
*/
function b2b(base64) {
var decode, i, length, byteArray;
i = 0;
decode = atob(base64);
length = decode.length;
byteArray = new Uint8Array(length);
for (;i < length;i++) {
byteArray[i] = decode.charCodeAt(i);
}
return new Blob([byteArray]);
}
/**
* 将base64数据解码并保存文件
* @param {string} base64 base64字符
* @param {string} filename 文件名
* @return {undefined}
*/
function saveAs(base64, filename) {
var a, blob, url;
a = self.document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
blob = b2b(base64);
url = self.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
self.URL.revokeObjectURL(url);
}
self.saveAs = saveAs;
})(self || window || this.content);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment