Creating a BLOB from a Base64 string in JavaScript

后端 未结 12 2633
说谎
说谎 2020-11-21 04:24

I have Base64-encoded binary data in a string:

const contentType = \'image/png\';
const b64Data = \'iVBORw0KGg         


        
12条回答
  •  长情又很酷
    2020-11-21 05:06

    I'm posting a more declarative way of sync Base64 converting. While async fetch().blob() is very neat and I like this solution a lot, it doesn't work on Internet Explorer 11 (and probably Edge - I haven't tested this one), even with the polyfill - take a look at my comment to Endless' post for more details.

    const blobPdfFromBase64String = base64String => {
       const byteArray = Uint8Array.from(
         atob(base64String)
           .split('')
           .map(char => char.charCodeAt(0))
       );
      return new Blob([byteArray], { type: 'application/pdf' });
    };
    

    Bonus

    If you want to print it you could do something like:

    const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // Or however you want to check it
    const printPDF = blob => {
       try {
         isIE11
           ? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
           : printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
       } catch (e) {
         throw PDFError;
       }
    };
    

    Bonus x 2 - Opening a BLOB file in new tab for Internet Explorer 11

    If you're able to do some preprocessing of the Base64 string on the server you could expose it under some URL and use the link in printJS :)

提交回复
热议问题