其他分享
首页 > 其他分享> > 前端通过流下载文件

前端通过流下载文件

作者:互联网

// file
export function downloadFile(data, name, suffix) {
  if (!name) {
    name = parseTime(new Date()) + '-' + name + '.xlsx';
  }
  // 对于IE浏览器特殊处理
  if (window.navigator && window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(new Blob([data]),name + (suffix ? ('.' + suffix) : ''));
  } else {
    const url = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    const fileName = name + (suffix ? ('.' + suffix) : '');
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}
// excel
export function downloadExcel(data, fileName,suffix) {
  let fix = suffix==undefined?'.xls':suffix
  fileName = parseTime(new Date()) + '-' + fileName;
  if (window.navigator && window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + fix)
  } else {
    let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName + fix)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link); //下载完成移除元素
    window.URL.revokeObjectURL(url); //释放掉blob对象
  }
}

标签:文件,suffix,前端,fileName,window,link,navigator,data,下载
来源: https://blog.csdn.net/qq_38899115/article/details/121610976