base64 - 如果文件太大,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。在这种情况下,它只会打开一个空白页面:
有谁知道为什么较大的文件无法打开?有没有更好的方法来解决这个问题?任何建议将不胜感激。
解决方案
您可以将太大的 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进行测试。
推荐阅读
- terraform-provider-aws - Terraform:如何支持不同的提供者
- reporting-services - ssrs 报告可折叠/可扩展分组
- python - 使用来自 Python 的 R 学习 Json 抓取
- java - 无法从带有 java 的 selenium webdriver 的下拉列表中选择选项
- javascript - currying 函数在 javascript 中的工作
- swift - 在下载实际图像时将占位符图像添加到 UICollectionView 单元格
- bash - 从命令的输出中捕获不同位置的子字符串
- kubernetes - Prometheus + Kubernetes 指标来自错误的抓取作业
- ios - ToView 在 Swift 中出现在 FromView 后面
- macos - 以编程方式实现 Mac 长按重音弹出