fileCreater.js
//文件导出:二进制数据文件化, Chrome有效,别的浏览器支持未知
//data:String BASE64编码的字符串
//fileName:String 文件名,包含文件类型(如:xxx.xls)
export function fileExport(data, fileName){
if(data == null){
return
}
if(!fileName){
fileName = 'file_'+now()+'.xls'
}else{
if(fileName.indexOf('${now}') !== -1){
fileName = fileName.replace('${now}',now());
}
}
//拿到文件名的后缀
let fileNameArray=fileName.split(".")
let fileType=fileNameArray[fileNameArray.length-1];
console.log(fileType);
let contentType="application/vnd.ms-excel";
switch(fileType){
case "xls":
contentType="application/vnd.ms-excel";
break;
case "xlsx":
contentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
case "csv":
contentType="text/csv";
break;
}
let binStr = window.atob(data),
n = binStr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = binStr.charCodeAt(n);
}
const blob = new Blob([u8arr], {type: contentType});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
}
function now(){
const now = new Date();
let year = now.getFullYear(),
month = now.getMonth()+1,
date = now.getDate(),
hour = now.getHours(),
min = now.getMinutes(),
sec = now.getSeconds();
month = month<10 ? '0'+month : month;
date = date<10 ? '0'+date : date;
hour = hour<10 ? '0'+hour : hour;
min = min<10 ? '0'+min : min;
sec = sec<10 ? '0'+sec : sec;
return ''+year+month+date+hour+min+sec;
}
使用fileCreater.js
import { fileExport } from "./fileCreater"
//data来自ajax请求的BASE64字符串
fileExport(data, "文件名[${now}].xls")