文件下载

发布时间 2023-06-07 17:55:08作者: 云霄紫潭

方式一、

  const url = 下载地址
  window.location.href = url

方式二、

/**
 * @method excel下载
 * @param  {String} type 需要下载的文件类型
 * @param  {Object} res  文件流
 * @param  {String} name 文件名
 * @return {NULL} 
*/
function createExcel(type,res, name) {
const blob = new Blob([data], {
    // type类型后端返回来的数据中会有,根据自己实际进行修改
    // 表格下载为 application/xlsx,压缩包为 application/zip等,
    type: type
  })
  let fileName = name;
  // 允许用户在客户端上保存文件
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
      var blobURL = window.URL.createObjectURL(blob)
    // 创建隐藏<a>标签进行下载
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    tempLink.setAttribute('download', fileName)
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)// 移除dom元素
    window.URL.revokeObjectURL(blobURL)// 释放bolb内存
  }
}

文件名获取

let fileName  = ""
if (res.headers["content-disposition"].indexOf("filename=")) {
          if (
            res.headers["content-disposition"].split("=")[1].indexOf("%") > -1
          ) {
            fileName = decodeURI(
              res.headers["content-disposition"].split("=")[1]
            );
          } else {
            fileName = res.headers["content-disposition"].split("=")[1];
          }
        }
     createExcel(res.data, fileName);

Excel Type类型:

  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

  • application/vnd.ms-excel

注意点:

使用方法二,需要在请求头或者请求接口上加:responseType:'blob',