文件下载

方式一、

  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',

https://blog.csdn.net/weixin_46018417/article/details/129026708
https://www.jianshu.com/p/ba8bcb96e7e2
https://devpress.csdn.net/viewdesign/640700e1986c660f3cf91597.html?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~activity-1-109131007-blog-129026708.235^v39^pc_relevant_3m_sort_dl_base4&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~activity-1-109131007-blog-129026708.235^v39^pc_relevant_3m_sort_dl_base4&utm_relevant_index=2

posted @ 2023-06-07 17:50  云霄紫潭  阅读(22)  评论(0编辑  收藏  举报