1

I am building a React project where a user needs to be able to preview a document that has been uploaded, converted to a Base64 binary data object and stored in a variable called 'upload'. I use the following code to display it in a new tab when the user clicks on the preview button:

var newWIndow;
if (upload.includes("data:application/pdf"))
    newWIndow = "<iframe width='100%' height='100%' src='" + upload + "'></iframe>"
else
    newWIndow = "<img width='100%' src='" + upload + "'></img>";
var x = window.open();
x.document.open();
x.document.write(newWIndow);
x.document.close();

The uploads are limited to image or pdf files. The preview works great, except when the file is PDF and the file size goes over 1MB. In that case, it simply opens a blank page:

enter image description here

Does anyone perhaps know why the larger files won't open? Is there a better way to approach this? Any advice would be very much appreciated.

2 Answers 2

1

I have found someone struggling with something similar in this post, specifically the answer posted by Himanshu Chawla.

I have updated my code as the following, which so far seems to work:

var byteCharacters = atob(upload.split(',')[upload.split(',').length - 1]);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
console.log(upload.split(',')[0].split(":")[1]);
var file = new Blob([byteArray], { type: upload.split(',')[0].split(":")[1] });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
1

You can convert your too big base64 pdf to blob, and then create a new URL from that blob.

Something like this upload is your base64 pdf string:

var url = 'data:application/pdf;base64,'+ upload ;
var blobUrl;
fetch(URL)
 .then(res => res.blob())
 .then(URL.createObjectURL)
 .then((ret) => {blobUrl=ret; return blobUrl;})
 .then(console.log)

This way you get a smaller URL from the same content.

One can test at this jsfiddle at example 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.