从 React fetch 调用获取文件名

Ric*_*ard 2 javascript filenames file reactjs fetch-api

fetch我正在React 中执行一个方法,它返回.pdf也已命名的文件,现在我想获取该文件名。

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

function showFile(blob, filename) {...}
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*ard 6

我最终用这个来代替。

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();
      });
    });
Run Code Online (Sandbox Code Playgroud)

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