我试图从服务器,将一个JSON里面包裹收到一个PDF。
如果我只是发送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
}
你应该字节转换为base64字符串和UI从中读取字节。
如果假定以下变量来表示的responseText的结构:
responseText = {
result: true,
value: <the pdf byte array>,
errorMessage: null
}
responseText.value
是字节数组。如果字节数组已经被分类为Uint8Array那么这会工作。
(注:其他Typed Arrays存在,所以选择过哪一个最适合你的情况):
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
事件触发时。
设置的字节数组的值作为字符串。在解析JSON转换串入字节数组。