【问题标题】:Typescript: fetch file from API and read it's original filenameTypescript:从 API 获取文件并读取它的原始文件名
【发布时间】:2019-08-26 02:20:53
【问题描述】:

我正在尝试使用 tslib 中的 fetch 方法从我在 react-typescript 应用程序中创建的 API 下载一些 Excel 文件。 这是下载代码:

export const getBlobCors = url =>
  tryAjax<Blob>(
    () =>
      fetch(url, {
        credentials: 'omit',
        headers: new Headers({
          ...getAuthHeader(),
          responseType: 'blob'
        })
      }),
    async response => {
      if (response.ok) {
        const blob = await response.blob()
        return blob
      } else {
        throw new Error(DefaultErrorMsg)
      }
    }
  )

从这里调用这个方法:

async function downloadReport(urlData: ReportUrlData) {
  const url = reportUrl(urlData)
  const blob = await getBlobCors(url)
  const blobUrl = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = blobUrl
  a.download = 'Report.xlsx'
  document.body.appendChild(a)
  a.click()
  setTimeout(() => {
    document.body.removeChild(a)
    window.URL.revokeObjectURL(blobUrl)
  })
}

正如你现在所看到的,文件名是硬编码的a.download = 'Report.xlsx',但我需要将它分配给 api 返回的文件名。 文件名确实存在于响应头中 但是当我尝试阅读 getBlobCors 响应时的方法时,我得到了 null,实际上 response.headers 是空的。

async response => {
      if (response.ok) {
        const fileName = response.headers.get('Content-Disposition') // null
        const headers = response.headers // Headers {}
        const blob = await response.blob()
        return blob
      } 

有谁知道如何从响应中读取文件名或我能得到的任何其他文件名?

【问题讨论】:

    标签: javascript reactjs typescript blob fetch


    【解决方案1】:

    在花了几乎一整天的时间之后,我找到了解决它的方法。问题出在我的后端。由于在 CORS 上使用 Fetch API 时访问响应标头存在限制,默认情况下仅允许访问预定义的标准标头列表,例如 Content-TypeContent-LanguageLast-ModifiedCache-ControlExpires 和 @ 987654326@。任何其他响应标头都需要在服务器上显式启用。在我的例子中,后端是 ASP.NET Core ,所以我在 Startup.cs 中添加了自定义 CORS 策略

    services.AddCors(o => o.AddPolicy("WithExposedContentDispositionHeader", builder =>
    {
         builder
         .AllowAnyOrigin()
         .WithExposedHeaders("content-disposition");
    }));
    

    并在控制器方法上启用此规则

     [EnableCors("WithExposedContentDispositionHeader")]
     public async Task<IActionResult> GetExcelReport([FromQuery] ReportInput input) {...}
    

    【讨论】:

      猜你喜欢
      • 2015-12-17
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 2011-01-01
      • 1970-01-01
      相关资源
      最近更新 更多