通过浏览器导出文件

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")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值