javascript - 如何在 JSON 中接收字节数组

标签 javascript angularjs json arraybuffer

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

最佳答案

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

关于javascript - 如何在 JSON 中接收字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54413038/

相关文章:

json - 检查 bash 脚本中 json 响应的值

javascript - 删除不同类型元素之前的所有同类型元素

javascript - 在 Angular 中通过 $scope 安全地使用 eval()

ios - 在 tableview 中显示来自 json 文件的图像

javascript - 谷歌 reCaptcha 不工作

javascript - 为什么 Angular-Cache 忽略容量配置?

javascript - 我想将现有的键值对放在对象的第一位

javascript - setTimeout 在再次运行之前在里面设置条件

javascript - 如何使用 npm 库中的 web-worker 到主 webpack 项目中

javascript - $http.post (angularjs) 中的未定义函数 : . 成功