最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting filename from React fetch call - Stack Overflow

programmeradmin2浏览0评论

I am doing a fetch method in React and It returns .pdf file that also is named and now I would like to get that filename.

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

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

How can I get the filename and call my function showFile with the filename?

I am doing a fetch method in React and It returns .pdf file that also is named and now I would like to get that filename.

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

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

How can I get the filename and call my function showFile with the filename?

Share Improve this question edited Jul 29, 2023 at 11:50 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 24, 2020 at 15:01 RichardRichard 1,1174 gold badges21 silver badges61 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

I ended up using this instead.

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();
      });
    });

The main problem I had here is that I forgot to expose Content-Disposition in my backend API which is why the React couldn't read the Content-Disposition and that gave me a lot of headache.

That blob should contain the file name also. You can get the name like this:

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
}
发布评论

评论列表(0)

  1. 暂无评论