如果文件太大,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。在这种情况下,它只会打开一个空白页面

enter image description here

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

解决方法

我发现有人在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);