如何在JSON中接收字节数组

时间:2019-01-29 02:33:02

标签: javascript angularjs json arraybuffer

我正在尝试从服务器接收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
}

3 个答案:

答案 0 :(得分:8)

如果假定以下变量表示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事件触发时下载文件。

答案 1 :(得分:7)

您应将字节转换为base64字符串,并在UI上从中读取字节。

答案 2 :(得分:-1)

将字节数组值设置为字符串。 解析JSON时,将字符串转换为字节数组。

请参考此Java Byte Array to String to Byte Array作为示例。