直接客户端浏览器下载文件,不必通过回传服务器再下载(例如将table内容导出excel)

时间:2021-01-03 19:19:00

//value:文件内容,type:文件类型,name:文件名
//(例如将table内容导出excel,可以生成xml格式的xls内容,然后直接调用这函数下载到客户端电脑)
function _ saveFile( value, type, name) {
var blob;
if ( typeof window. Blob == "function") {
blob = new Blob([ value], { type: type});
} else {
var BlobBuilder = window. BlobBuilder || window. MozBlobBuilder || window. WebKitBlobBuilder || window. MSBlobBuilder;
var bb = new BlobBuilder();
bb. append( value);
blob = bb. getBlob( type);
}
var URL = window. URL || window. webkitURL;
var bloburl = URL. createObjectURL( blob);
var anchor = document. createElement( "a");
if ( 'download' in anchor) {
anchor. style. visibility = "hidden";
anchor. href = bloburl;
anchor. download = name;
document. body. appendChild( anchor);
var evt = document. createEvent( "MouseEvents");
evt. initEvent( "click", true, true);
anchor. dispatchEvent( evt);
document. body. removeChild( anchor);
} else if ( navigator. msSaveBlob) {
navigator. msSaveBlob( blob, name);
} else {
location. href = bloburl;
}
}