简体   繁体   中英

React - the downloaded pdf is blank

At first, I send a GET request for the pdf data

const config = {
  headers: {
    'Content-Type': 'application/json',
     Accept: 'application/json',
  },
  baseURL: 'https://my-site.com',
};
const axiosInstance = axios.create({config});
 
const pdf = await axiosInstance.get('url', {
        headers: { Authorization: 'Bearer ' + accessToken, Accept: '*/*' },
})

The value of pdf is the same as below
在此处输入图像描述

Then I tried to download the file

    const url = window.URL.createObjectURL(new Blob([pdf]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `FileName.pdf`);

    // Append to html link element page
    document.body.appendChild(link);

    // Start download
    link.click();

I can download the pdf file successfully, but the pdf is blank when I open it.

How to fix it?

Fix it by adding responseType: 'blob'

const pdf = await axiosInstance.get('url', {
        headers: { Authorization: 'Bearer ' + accessToken, Accept: '*/*' },
        responseType: 'blob',
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM