如果文件太大,URL 字符串中的 Base64 二进制数据打开空白页

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

我正在构建一个 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。在这种情况下,它只会打开一个空白页面:

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

我发现有人在 this post 中遇到类似的问题,特别是 Himanshu Chawla 发布的答案。

我已将我的代码更新如下,到目前为止似乎有效:

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

您可以将太大的 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 中测试 at this jsfiddle