我正在尝试从服务器接收 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();
}
}
但是,当服务器尝试发送带有字节数组的 JSON 时,如果我将 responseType
设置为 JSON
,那么我将无法转换 blob。但是,如果我将 responseType
设置为 arrayBuffer
,我将得到一个 arrayBuffer 数组,如何将其转换为 JSON,同时仍然能够提取 PDF:
我收到的 JSON 格式如下:
{
result: true,
value: <the pdf byte array>,
errorMessage: null
}
原文由 user1294510 发布,翻译遵循 CC BY-SA 4.0 许可协议
您应该将字节转换为 base64 字符串,并在 UI 上从中读取字节。