javascript - 如何在 JavaScript 中将“原始”字节写入浏览器?
问题描述
我正在尝试向用户提供 PDF 文件,并且我有一个包含 PDF 文件中字节的字符串。我想将这些字节写入浏览器,以便用户下载 PDF 文件。但是,当我这样做时:
document.open('application/pdf');
document.write(myBytes);
我只是将字节呈现为文本,也就是说,它们位于 HTML 页面中(参见屏幕截图)。我只想渲染指定的字节,而不需要围绕它们的任何 HTML。我怎样才能做到这一点?
解决方案
anchor
您可以使用&&download
属性技巧或使用强制文件下载iframe
下面是一个例子
由于沙盒环境,代码段不起作用。
const pdfView = document.querySelector("#pdfView");
fetch("https://cors-anywhere.herokuapp.com/https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")
.then(response => response.blob())
.then(blob => blob.arrayBuffer())
.then(myBytes => {
const totalBlob = new Blob([myBytes], { type: 'application/pdf' });
const url = window.URL.createObjectURL(totalBlob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `document.pdf`;
anchor.click();
anchor.textContent = 'Download'
document.body.appendChild(anchor);
pdfView.src = url;
})
<iframe id="pdfView" src="" type="application/pdf" width="100%" height="100%" style="overflow: auto;">
</iframe>
推荐阅读
- node.js - 使用带有 npm 的护照包可以从客户端更改 req.user 对象吗?
- angular - Angular - 用于同一组件中的两个元素时,ngx剪贴板抛出错误
- flutter - 取消飞镖中的请求
- python - 没有数据库的烧瓶登录
- android-studio - 如何获取当前连接的 wi-fi 网络的 SSID 和 PASSWORD
- sql - 如何在 SQL 中存储 Json 查询?
- azure - Docker:你可以拥有的 build-arg 的数量有限制吗?
- websocket - 房间里的 Socket Ids 不稳定
- python - 使用验证集测试模型的泛化能力
- python - Python:如何使用 openCV 修复图像中的杂乱区域?