Rinchen
Rinchen

Reputation: 27

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);
    }
  });

Upvotes: 0

Views: 4481

Answers (3)

Carlos Júlio
Carlos Júlio

Reputation: 525

Following dchang suggestion, here is what worked form me:

function base64ToBlob(base64String, contentType = '') {
// Remove data URL prefix if it exists
var base64Data = base64String.replace(/^data:([^;]+);base64,/, '');

// Convert base64 to raw binary data
var binaryData = atob(base64Data);

// Create array buffer from binary data
var arrayBuffer = new ArrayBuffer(binaryData.length);
var uint8Array = new Uint8Array(arrayBuffer);

// Fill array buffer with binary data
for (let i = 0; i < binaryData.length; i++) {
  uint8Array[i] = binaryData.charCodeAt(i);
}

// Create blob from array buffer
var blob = new Blob([arrayBuffer], { type: contentType });

// Create and return blob URL
return URL.createObjectURL(blob);
}

var blobUrl = base64ToBlob(base64str, 'application/pdf');

imageContainer.innerHTML = `
    <iframe src="${blobUrl}"></iframe>`;

Upvotes: 0

dchang
dchang

Reputation: 1141

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

Upvotes: 1

Bob  Sponge
Bob Sponge

Reputation: 4738

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 + '">'
);

Upvotes: 1

Related Questions