Search code examples
base64binary-datarect

Base64 binary data in an URL string opening blank page if file too large


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.


Solution

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