Pdf file corrupt after downloding

2.8k Views Asked by At

I am using Sharetribe platform that I can't touch the server code but only get access on custom script. So I use jquery ajax to upload and download files to dropbox. The upload process went smooth but the download one has an issue that the downloaded file is corrupt. It can't be opened by any pdf software. I also found the size of the file bigger than the original pdf file in my dropbox. The original pdf file is good and can be opened perfectly.  

Here is the code to download the file 

var url = 'https://content.dropboxapi.com/2/files/download';

$.ajax({
    url: url,
    type: 'post',
    responseType: 'arraybuffer',
    headers: {
        "Authorization": "Bearer <TOKEN>",
        "Dropbox-API-Arg": JSON.stringify({"path": "/"+filename})
    },
    success: function (data){
        console.log(data);
        //CAN DOWNLOAD PDF BUT CAN'T OPEN IT. FILE PDF IS CORRUPT
        //var blob = new Blob([data]);
        //var aLink = document.createElement('a');
        //aLink.href = window.URL.createObjectURL(blob);
        //aLink.download = "file_tc.pdf";
        //aLink.click();        
        const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }));
        window.open(url);
    },
    error: function (data){
        console.log(data);
    }
})

Anyone can help what's wrong with the above code?

1

There are 1 best solutions below

0
On

I read http://keyangxiang.com/2017/09/01/HTML5-XHR-download-binary-content-as-Blob/. I found ordinary jquery ajax not support blob or arraybuffer. Then I added beforeSend handler as suggested but still not working so I use XMLHTTPRequest instead. It's working well. I got the correct pdf file and size. Here is my code changes:

var url = 'https://content.dropboxapi.com/2/files/download';
var token = 'YOUR-ACCESS-TOKEN';

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var url = (window.URL || window.webkitURL).createObjectURL(xhr.response);
        var aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.href = url;
        aLink.download = filename;
        aLink.click();
    }
};
xhr.open('POST', 'https://content.dropboxapi.com/2/files/download');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({"path": "/"+filename}));
xhr.send();

Hopefully this would help someone that stumble the same problem.