首页 > 解决方案 > 如果文件太大,URL 字符串中的 Base64 二进制数据会打开空白页

问题描述

我正在构建一个 React 项目,用户需要能够预览已上传、转换为 Base64 二进制数据对象并存储在名为“upload”的变量中的文档。当用户单击预览按钮时,我使用以下代码将其显示在新选项卡中:

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

上传仅限于图像或 pdf 文件。预览效果很好,除非文件是 PDF 并且文件大小超过 1MB。在这种情况下,它只会打开一个空白页面:

在此处输入图像描述

有谁知道为什么较大的文件无法打开?有没有更好的方法来解决这个问题?任何建议将不胜感激。

标签: base64binary-datarect

解决方案


您可以将太大的 base64 pdf 转换为 blob,然后从该 blob 创建一个新 URL。

像这样的东西upload是你的 base64 pdf 字符串:

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)

通过这种方式,您可以从相同的内容中获得更小的 URL。

可以在示例 2中的这个 jsfiddle进行测试。


推荐阅读