Good day!

The essence of the problem is described in the title.

Now, I have an action from the React component after the click is passed to action, where I get a request to the backend using async-await. Then, if everything is ok, then I send response.data (my pdf) to dispatch, then with the help of a helper, create an invisible link, click on it and the file is downloaded, but it is empty. It was checked on different files, everywhere a pdf file with empty pages is being downloaded (I note that there are as many pages as there are in the real document). Suspicion that something is wrong with the encodings, but I can not find the error. I’m implementing this for the first time, so at the dead end I don’t know how to find a way out of this problem.

Here is my code:

My Action

export const request = createAction(DOWNLOAD_PDF); export const success = createAction(DOWNLOAD_PDF_SUCCESS, ({ response, id }) => { fileDownload(response, `return-${id}.pdf`); // Мой хелпер return { payload: { data: response, id } }; }); export const failure = createAction(DOWNLOAD_PDF_FAIL); export default ({ id }) => { return async dispatch => { try { dispatch(request()); const response = await returns.getPdf({ id }); dispatch(success({ response: response.data, id })); } catch (error) { dispatch( failure({ payload: { message: 'Неудалось скачать PDF', stack: error.stack, }, }), ); errorLogger(error, DOWNLOAD_PDF); } }; }; 

My helper:

 export default function (data, fileName, format = 'utf-8') { if (typeof window.navigator.msSaveBlob !== 'undefined') { const byteNumbers = new Array(data.length); // save file in IE or edge for (let i = 0; i < data.length; i += 1) { byteNumbers[i] = data.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray], { type: format }); navigator.msSaveBlob(blob, fileName); return; } let url = `data:application/pdf;charset=${format}`; if (format === 'windows-1251') { url += `;base64,${btoa(data)}`; } else { url += `,${encodeURIComponent(data)}`; } const tempLink = document.createElement('a'); tempLink.href = url; tempLink.setAttribute('download', fileName); tempLink.setAttribute('target', '_blank'); document.body.appendChild(tempLink); tempLink.click(); document.body.removeChild(tempLink); } 

Any help would be very valuable!

    1 answer 1

    In general, there was a solution. Walked around it many times.

    The problem was that I had a separate file that creates my header and httpConfig in the request and all I had to do was add responseType there: 'blob'

    Like this

     export const getPdfConfig = axios.create({ ...httpConfig, responseType: 'blob', headers: { ...customHeaders, 'Content-Type': 'application/pdf', }, }).get; 

    Well then use fileSaver.