skip to Main Content

I get base64 encode data from the server which I need to show a preview of that pdf file in new tab on click. File can be in pdf with size 6 MB. In the Url on open it is turncated.

<a href="data:image/png;base64,..." target="_blank">preview</a>

How Can I show the base64 encode data in a new tab?

I found this Show base64 encoded data in new tab Rails which is not clear yet.

I am using reactjs and javascript

const signatures = {
    JVBERi0: "application/pdf",
    R0lGODdh: "image/gif",
    R0lGODlh: "image/gif",
    iVBORw0KGgo: "image/png",
    "/9j/": "image/jpg"
  };
  const detectMimeType= (b64) => {
    for (var s in signatures) {
      if (b64.indexOf(s) === 0) {
        return signatures[s];
      }
    }
    return null;
  }
const showPreview = (e,base64_data) => {
    e.preventDefault();
    const mime_type = detectMimeType(base64_data);
    let data = "data:"+mime_type+";base64," + base64_data;
    var w = window.open("");
      w.document.write(data);
    
  }

I am not getting any error with showPreview it is printing the data uri to the page.

2

Answers


  1. Chosen as BEST ANSWER

    This actually worked to me. I converted the uri to blob and blob opened in a new window

    const showPreview = (e,base64_data) => {
        e.preventDefault();
        const mime_type = detectMimeType(base64_data);
        let data = "data:"+mime_type+";base64," + base64_data;
        let blobData = dataURLtoBlob(data);
        var w = window.open('about:blank');
        w.location = URL.createObjectURL(blobData);
          
      }
      const dataURLtoBlob=(dataurl) => {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type:mime});
      }
    

  2. Data URIs have a length limit in browsers (which I don’t recall) so what you can do to overcome this is to convert the Data URI to a blob-URL like this…

    function DataUri2Blob(dataURI){
    
    var B=atob(dataURI.split(',')[1]), L=B.length, A=[];
    
    var Mime=dataURI.split(',')[0].split(':')[1].split(';')[0];
    
    for(let i=0; i<L; i++){A.push(B.charCodeAt(i));}
    
    return new Blob([new Uint8Array(A)],{type:Mime});}
    

    Usage…

    var dataURI='data:image/png;base64,.....';
    
    let Blob=DataUri2Blob(dataURI);
    
    let Url=URL.createObjectURL(Blob);
    

    And then fire up the Url variable in a new window/tab.

    And two seconds later…

    URL.revokeObjectURL(Url);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search