'Base64 is too large to open in a browser, any alternatives?
My base64 PDF is too large that when I try and open it in a window, the url isn't pasted. I then substring'd it and the link would paste but of course.. it doesn't open as it hasn't received the whole base64.
Code:
$.ajax({
url: [database-url-here],
type: 'GET',
dataType: 'json',
success: function(data){
var pdf = (data.pdf).toString();
window.open(pdf);
}
});
Solution 1:[1]
var w = window.open('', '', 'width=400,height=240'); // open blank page
w.document.write(
'<embed type="application/pdf" ' +
'width="400" height="240" ' +
'src="data:application/pdf;base64,' + pdf + '">'
);
Solution 2:[2]
For too big base64 pdf files I convert it to blob and then create a new URL from that blob. Blob URL is much smaller then base64 url.
To convert I do something like this:
var url = 'data:application/pdf;base64,'+ base64string;
var blobUrl;
fetch(URL)
.then(res => res.blob())
.then(URL.createObjectURL)
.then((ret) => {blobUrl=ret; return blobUrl;})
.then(console.log)
One can test at this jsfiddle at example 2. Or see other alternatives here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bob Sponge |
| Solution 2 | dchang |
