如果文件太大,URL字符串中的Base64二进制数据将打开空白页 [英] Base64 binary data in an URL string opening blank page if file too large

查看:355
本文介绍了如果文件太大,URL字符串中的Base64二进制数据将打开空白页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a React project where a user needs to be able to preview a document that has been uploaded, converted to a Base64 binary data object and stored in a variable called 'upload'. I use the following code to display it in a new tab when the user clicks on the preview button:

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

The uploads are limited to image or pdf files. The preview works great, except when the file is PDF and the file size goes over 1MB. In that case, it simply opens a blank page:

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

Does anyone perhaps know why the larger files won't open? Is there a better way to approach this? Any advice would be very much appreciated.

推荐答案

我发现有人在

I have found someone struggling with something similar in this post, specifically the answer posted by Himanshu Chawla.

我将代码更新如下,到目前为止似乎可以正常工作:

I have updated my code as the following, which so far seems to work:

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

这篇关于如果文件太大,URL字符串中的Base64二进制数据将打开空白页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆