javascript - 如何在 JSON 中接收字节数组
问题描述
我正在尝试从服务器接收 PDF,该 PDF 将包装在 JSON 中。
如果我只是将 pdf 的字节数组发送到前端,我可以通过设置responseType
为正确读取它arraybuffer
,然后我可以通过以下方式下载 PDF:
var blob = new Blob([data], { type: application/pdf});
if ($window.navigator && $window.navigator.msSaveOrOpenBlob) {
$window.navigator.msSaveOrOpenBlob(blob);
} else {
var a = document.createElement("a");
document.body.appendChild(a);
var fileURL = URL.createObjectURL(blob);
a.href = fileURL;
a.download = fileName;
a.click();
}
}
但是,当服务器尝试发送带有 bytearray 的 JSON 时,如果我将其设置responseType
为JSON
,那么我将无法转换 blob。但是如果我设置responseType
为arrayBuffer
,我将得到一个 arrayBuffer 数组,我如何将它转换为 JSON,同时仍然能够在之后提取 PDF:
我收到的 JSON 格式如下:
{
result: true,
value: <the pdf byte array>,
errorMessage: null
}
解决方案
如果假设下面的变量代表 responseText 的结构:
responseText = {
result: true,
value: <the pdf byte array>,
errorMessage: null
}
responseText.value
是字节数组。如果字节数组已经被输入为 Uint8Array 那么这将起作用。
(注意:存在其他类型的数组,因此请选择最适合您情况的数组):
var blob = new Blob([response.value], { type: 'application/pdf'});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
} else {
var a = document.createElement("a");
document.body.appendChild(a);
var fileURL = URL.createObjectURL(blob);
a.href = fileURL;
a.download = 'test';//filename
a.click();
}
但是,如果存在如下字节的字符串数组或整数数组:
responseText.value = [145, 229, 216, 110, 3]
并且需要将其转换为类型化的字节数组,然后以下将起作用:
var ba = new Uint8Array(responseText.value);
或者
var ba = new Uint8Array([145, 229, 216, 110, 3]);
所以,
var blob = new Blob([ba], { type: 'application/pdf'});
这样,字节数组可用于创建 blob,因此在click
事件触发时会下载文件。
推荐阅读
- python - 在 Windows 启动时运行 python 脚本
- javascript - 如何在功能组件中立即更新反应状态?
- javascript - 如何对 PHP 计时声音?
- php - 使用 Laravel 将大文件上传到 S3 的问题
- wordpress - 为什么我无法在 Windows 10 上访问 IIS 中的根目录以外的内容?
- javascript - 使用 discord.js 查找不和谐消息的内容
- html - 在 Safari 和 Firefox 中拖动溢出 div 的内容滚动,而不是在 Chrome 中
- r - 使用 R 取消嵌套 JSON
- azure-web-app-service - 无论部署的实际实例如何,用户是否始终按照 Azure 应用服务计划的最大实例限制付费?
- python - 给定一个点和大量的四面体,如何高效判断该点在哪个四面体中