如何下载或打开需要验证的url

225 阅读1分钟

后端接口不带token

这种最简单 使用window.open('/api/download_template')

后端get接口需要带token

这种是下载xlsx文件到本地,打开可以修改,另存为

fetch('/api/download_template', {
    // responseType: 'blob',
    headers: {
      'Authorization': token.get(),
    },
  })
      .then(res => {
        if (!res.ok) {
          throw new Error(res.statusText);
        }
        return res.blob()
      })
      .then(res =>  {
        const blob = new Blob([res])
        let fileName = Date.parse(new Date())+".xlsx";
        let link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
        // document.body.removeChild(link);
      })
复制代码

如果需要自动打开,需要指定blob格式:

MIME types:

  • application/vnd.ms-excel (official)(xls)
  • application/msexcel
  • application/x-msexcel
  • application/x-ms-excel
  • application/x-excel
  • application/x-dos_ms_excel
  • application/xls
  • application/x-xls
  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (xlsx)
  fetch('/api/segment/sedimentation_point_template', {
    responseType: 'blob',
    headers: {
      'Authorization': token.get(),
    },
  })
      .then(res => res.blob())
      .then(res =>  {
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const fileURL = URL.createObjectURL(blob);
        window.open(fileURL);
      })