将字节数组写入文件 JavaScript

use*_*595 5 javascript arrays rest xmlhttprequest download

我有 Java REST Web 服务,它以字节数组的形式返回文档,我需要编写 JavaScript 代码来获取 Web 服务的响应并将其写入文件,以便将该文件下载为 PDF 请查看 Web 服务响应的屏幕截图并查看我的示例代码 此代码下载损坏的 PDF 文件。

var data = new FormData();
data.append('PARAM1', 'Value1');
data.append('PARAM2', 'Value2');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'SERVICEURL');
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
xhr.onload = function() {
    
    console.log('Response text = ' + xhr.responseText);
    console.log('Returned status = ' + xhr.status);
    
    
    var arr = [];
    arr.push(xhr.responseText);

    var byteArray = new Uint8Array(arr);
    var a = window.document.createElement('a');
    a.href = window.URL.createObjectURL(new Blob(byteArray, { type: 'application/octet-stream' }));
    a.download = "tst.pdf";
    // Append anchor to body.
    document.body.appendChild(a)
    a.click();
    // Remove anchor from body
    document.body.removeChild(a)
    
};
xhr.send(data);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Vin*_*ney 4

由于您请求的是二进制文件,因此您需要告诉 XHR,否则它将使用默认的“文本”(UTF-8) 编码,该编码会将 pdf 解释为文本并会弄乱编码。只需为responseType属性分配“blob”值或 pdf 的 MIME 类型

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // tell XHR that the response will be a pdf file

// OR xhr.responseType = 'application/pdf'; if above doesn't work
Run Code Online (Sandbox Code Playgroud)

您将使用responseproperty 而不是来访问它responseText。所以你会使用它arr.push(xhr.response);,它会返回一个 Blob。

如果这不起作用,请通知我将更新另一个解决方案。

更新:

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // tell XHR that the response will be a pdf file
xhr.onload = function() {
    var blob = this.response;
    var a = window.document.createElement('a');
    a.href = window.URL.createObjectURL(blob);
    a.download = "tst.pdf";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
};
Run Code Online (Sandbox Code Playgroud)