使用Laravel和Reactjs从服务器下载文件,得到空PDF

问题描述 投票:0回答:1

使用axios调用API下载pdf。我可以下载文件,但没有内容

await axios.post(URL,
         
          JSON.stringify({ filter }),
          {
            headers: {
              Authorization: token,
              'Content-Type': 'application/json'
            },
            withCredentials: true
          }
      ).then((response) => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'expense.pdf');
        document.body.appendChild(link);
        link.click();
      });
reactjs pdf axios pdf-generation
1个回答
0
投票

已经找到解决方案了!问题在于内容类型。我将其设置为 blob 并将其放在标题之外。以下代码现在工作正常。

await axios.post(URL,
         
          JSON.stringify({ filter }),
          {
            headers: {
              Authorization: token
            },
            responseType: 'blob',
            withCredentials: true
          }
      ).then((response) => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'expense.pdf');
        document.body.appendChild(link);
        link.click();
      });

© www.soinside.com 2019 - 2024. All rights reserved.