从 React 获取调用获取文件名

Getting filename from React fetch call

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

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

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

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

该 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
}

我最终改用了这个。

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 和这让我很头疼。