kosbr
kosbr

Reputation: 388

javascript ajax pdf download returns empty document

I've a request that returns pdf file. It can be well displayed in a browser, downloaded by curl.

My react frontend application call this request (ajax), and returns it to a user.

This is how do I call it:

httpRequest({
    method: 'GET',
    responseType: 'blob',
    url: `/test/pdf?` +
            `param1=${var1}&` +
            `param2=${var2}`
});

This is httpRequest:

export const httpRequest = (options) => {
return new Promise((resolve, reject) => {
    const contentType = options.contentType ? options.contentType : 'application/x-www-form-urlencoded';
    request.open(options.method, options.url, async);
    request.setRequestHeader('Content-Type', contentType);
    request.onreadystatechange = () => {
        if (request.readyState === readyState && request.status === status) {
            switch (responseType) {
                case 'json': {
                    if (request.responseText) {
                        resolve(JSON.parse(request.responseText));
                    } else {
                        throw new Error('Can not parse JSON!');
                    }
                    break;
                }
                case 'string': {
                    resolve(request.responseText);
                    break;
                }
                case 'blob': {
                    resolve(request.response)
                }
                default: {
                    resolve(request);
                    break;
                }
            }
        }
    };
    request.send(data);
});

};

Having the response, I return it to a user:

const link = document.createElement('a');
const file = new Blob([response.response], { type: 'application/pdf' });

link.href = window.URL.createObjectURL(file);
link.download = `test.pdf`;
document.body.appendChild(link);
link.click();

It returns me empty pdf (two empty pages). Its size in bytes is near 2 times bigger, than the normal pdf with content (I got it from curl).

Here is typical difference between two pdfs (good is left, bad is right) http://storage5.static.itmages.com/i/18/0125/h_1516888730_3382943_f47d4f9cbe.png

What is wrong in my code? Any workarounds?

Upvotes: 0

Views: 2130

Answers (1)

Anzhela
Anzhela

Reputation: 26

It looks as if the returning the response part is ok, so try to check the httpRequest() - if parameters, e.g responseType, are applied correctly. Please share the code, it could be more informative.

Upvotes: 1

Related Questions