【问题标题】:Getting filename from React fetch call从 React fetch 调用中获取文件名
【发布时间】:2020-07-05 02:26:32
【问题描述】:

我在 React 中执行 fetch 方法,它返回同样命名的 .pdf 文件,现在我想获取该文件名。

function downloadPdf() {
    fetch(BASE_URL + `/example/example/pdf/${exampleId}`)
      .then(r => r.blob())
      .then(showFile);
}

function showFile(blob, filename) {...}

如何获取文件名并使用文件名调用我的函数showFile

【问题讨论】:

    标签: reactjs api file fetch filenames


    【解决方案1】:

    我最终改用了这个。

    fetch(BASE_URL + `/example/example/pdf/${exampleId}`)
      .then(response => {
          const filename =  response.headers.get('Content-Disposition').split('filename=')[1];
          response.blob().then(blob => {
            let url = window.URL.createObjectURL(blob);
            let a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.click();
          });
        });
    

    我在这里遇到的主要问题是我忘记在我的后端 API 中公开 Content-Disposition,这就是为什么 React 无法读取 Content-Disposition 这让我很头疼。

    【讨论】:

      【解决方案2】:

      那个 blob 也应该包含文件名。 你可以得到这样的名字:

      function downloadPdf() {
          fetch(BASE_URL + `/example/example/pdf/${exampleId}`)
            .then(r => r.blob())
            .then(showFile(r));
      }
      
      function showFile(fileReceived) {
        let filename = fileReceived[0].filename;
        // other operations
      }
      

      【讨论】:

      • 我收到此错误:Unhandled Rejection (TypeError): Cannot read property 'filename' of undefined。但是当我查看网络检查选项卡中的文件时,我仍然可以清楚地看到它在那里。 attachment; filename=myfileName.pdf
      • 实际上这个解决方案可能有效,因为我之前没有暴露过Content-Disposition
      猜你喜欢
      • 2019-04-02
      • 2012-05-03
      • 2018-08-23
      • 2020-10-04
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2021-07-26
      • 2019-11-09
      相关资源
      最近更新 更多