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

javascript - How to download a file from an api in react - Stack Overflow

programmeradmin0浏览0评论

How to download a file from an API response which is in a different format ?

await axios.get(`/dashboard/reportdownload/?file_name=242424242.pdf`,{
            headers: {
              "Authorization": `Bearer 767958756576576576jgjhgjhg`
            }
          })
          .then((res) => {
            console.log(res?.data);
          });

In response I am getting

How do download it with reactjs

How to download a file from an API response which is in a different format ?

await axios.get(`/dashboard/reportdownload/?file_name=242424242.pdf`,{
            headers: {
              "Authorization": `Bearer 767958756576576576jgjhgjhg`
            }
          })
          .then((res) => {
            console.log(res?.data);
          });

In response I am getting

How do download it with reactjs

Share Improve this question edited Aug 30, 2022 at 7:12 Gregoire Ducharme 1,10613 silver badges26 bronze badges asked Aug 30, 2022 at 6:35 learner62learner62 6104 gold badges12 silver badges28 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 6

You need to check if the response from the API is of type blob, then convert it. For example, if it is clear you are expecting a PDF response, try this:

await axios.get(`/dashboard/reportdownload/?file_name=242424242.pdf`, {
  headers: {
    'Authorization': `Bearer 767958756576576576jgjhgjhg`
  }
})
  .then((response) => {
    let fileName = '242424242.pdf';
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      // IE variant
      window.navigator.msSaveOrOpenBlob(
        new Blob([response.data], {
          type: 'application/pdf',
          encoding: 'UTF-8'
        }),
        fileName
      );
    } else {
      const url = window.URL.createObjectURL(
        new Blob([response.data], {
          type: 'application/pdf',
          encoding: 'UTF-8'
        })
      );
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
  });
发布评论

评论列表(0)

  1. 暂无评论