【问题标题】:Base64 is too large to open in a browser, any alternatives?Base64 太大,无法在浏览器中打开,有什么替代方案吗?
【发布时间】:2016-06-18 02:51:51
【问题描述】:

我的 base64 PDF 太大,当我尝试在窗口中打开它时,没有粘贴 URL。然后我对它进行了子串化,链接会粘贴,但当然..它没有打开,因为它没有收到整个 base64。

代码:

   $.ajax({
    url: [database-url-here],
    type: 'GET',
    dataType: 'json',
    success: function(data){
      var pdf = (data.pdf).toString();

      window.open(pdf);
    }
  });

【问题讨论】:

    标签: javascript pdf base64 blob


    【解决方案1】:
    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 + '">'
    );
    

    【讨论】:

    • 不起作用:/base64 仍然没有粘贴到浏览器 URL 中。
    • pdf 变量中的数据可能格式不正确。或者,如果您尝试过window.open(pdf);,您也可以尝试以这种方式设置src'src="' + pdf + '"&gt;'(如果data:application/pdf;base64, 已经在pdf 变量中)。
    • 我已经在 Firefox 中测试了这段代码,它对我有用。
    • 它可以工作,但是当浏览器的base64字符太多时它不会粘贴它
    • 是的,5mb pdf 打开大约 20 秒。你也可以试试github.com/mozilla/pdf.js
    【解决方案2】:

    对于太大的 base64 pdf 文件,我将其转换为 blob,然后从该 blob 创建一个新 URL。 Blob URL 比 base64 url​​ 小得多。

    要转换,我会这样做:

    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)
    

    可以在示例 2 中测试 at this jsfiddle。 或查看其他替代方案here

    【讨论】:

      猜你喜欢
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多