rndme / download

file downloading using client-side javascript
MIT License
2.29k stars 417 forks source link

Downloadjs breaks PDF file #8

Closed ashl1 closed 8 years ago

ashl1 commented 9 years ago

The library breaks PDF file and produces invalid PDF which opens with blank pages. PDF Example: http://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf

Code:

$.ajax({
        url: '/AdobeXMLFormsSamples.pdf',
        success: download.bind(true, "application/pdf", 'AdobeXMLFormsSamples.pdf'), 
        complete: function(){...}
    });

Tested on browsers:

skibz commented 9 years ago

@ashl1 this isn't a bug in the library, your code isn't giving the download function a data source. the problem is here:

success: download.bind(true, "application/pdf", 'AdobeXMLFormsSamples.pdf'),

it ought to be:

complete: function(event, xhr, settings) {
    download(xhr.responseHTML, 'application/pdf', 'AdobeXMLFormsSamples.pdf');
}
nullifiedaccount3 commented 9 years ago

@skibz It should be as below right?

complete: function(event, xhr, settings) {
    download(xhr.responseHTML, 'AdobeXMLFormsSamples.pdf',  'application/pdf');
}
skibz commented 9 years ago

@bhargav3 ah, yes, well-spotted. i mixed up the mimetype and file name arguments!

nullifiedaccount3 commented 9 years ago

Hi @skibz I'm trying to do this for word and excel files but all I get is the string as it is in the file. Strangely PDFs are working. Any idea why this might be happening?

rndme commented 8 years ago

binary files are a problem for jQuery ajax. see my last post on https://github.com/rndme/download/issues/4 for a vanilla workaround. i'm getting a strong sense that there's a need to be able to simply feed download() a url, and i'll see what i can do about that...

nullifiedaccount3 commented 8 years ago

@rndme I was able solve this problem by converting data URI to blob and passing it to Downloadjs like below,

dataURItoBlob = function (dataURI) {
                    var byteString = atob(dataURI.split(',')[1]),
                            mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0],
                            ab = new ArrayBuffer(byteString.length),
                            ia = new Uint8Array(ab);
                    for (var i = 0; i < byteString.length; i++) {
                        ia[i] = byteString.charCodeAt(i);
                    }
                    return new Blob([ab], {'type': mimeString});
                };

download(dataURItoBlob(dataURI), filename, mimetype);