I want to download PDF document with JavaScript and using blob as described here. If I download my PDF directly without JS, I receive a working PDF, but if I download it with JavaScript by using blob I cannot open my PDF. I tested it on Mozilla Firefox 68.0.2 (64-Bit) and Google Chrome 76.0.3809.132 (Official Build) (64-Bit) and it didn't work.
I tested different Content-Type headers, but wasn't able to resolve that issue. I tested with:
- text/plain
- text/html
- data:attachment/text
- application/pdf
My test server is returning those headers:
HTTP/1.1 200 OK
Content-Disposition: attachment;filename=document.pdf
Content-Type: application/pdf
Content-Length: 577479
I tried also to set encoding to UTF8, but the result was the same.
I'm requesting it with AJAX (maybe problem is somewhere here?) and I'm using jQuery v3.3.1.
$.ajax({
type : "GET",
url : pdfDownloadURL,
async : true,
success : function(blob) {
var contentType = "attachment/pdf";
try {
var blob = new Blob([blob], {type: contentType});
} catch (e) {
// The BlobBuilder API has been deprecated in favour of Blob, but older
// browsers don't know about the Blob constructor
// IE10 also supports BlobBuilder, but since the `Blob` constructor
// also works, there's no need to add `MSBlobBuilder`.
var BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder;
var bb = new BlobBuilder();
bb.append(blob);
var blob = bb.getBlob(contentType);
}
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.target = "_blank";
link.style = "display: none";
link.download = "document2.pdf";
document.body.appendChild(link);
link.click();
},
// ...
});
document1.pdf (downloaded directly)
document2.pdf (downloaded using JavaScript blob method)
I checked requests with sniffing tool fiddler and server is returning always the same document, so the problem must be somewhere in my JavaScript part. As you can see in the red boxes - those bytes are the same, but then we have diffetent bytes, but I saw that server returned in both cases the same document, so this problem is only on the client side.
- Size of document1.pdf (OK):
577.479
bytes - Size of document2.pdf (broken):
1.034.166
bytes
Then I try to open document2.pdf with google chrome 76.0.3809.132, 64-Bit and it fails.
Is there a problem with my version of jQuery (in that AJAX part)?