小编Sta*_*tch的帖子

如何将 JavaScript 中的数据缓冲区转换为文件?

我正在从客户端的节点/express 端点接收数据缓冲区,并且我想将缓冲区转换为文件。

该文件可以是 pdf、文本文档或图像。端点告诉我的唯一信息是它正在发送一个八位字节流。

我该怎么做呢?

这是我迄今为止在客户端的代码

const xhr = new XMLHttpRequest();
xhr.open("POST", "MY_URL", true);
xhr.responseType = "arraybuffer";

// I need to send some data for the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

// send request
xhr.send(`identifier=${myIdentifier}`);

xhr.onload = function (xEvent)
{
    const arrayBuffer = xhr.response;
    if (arrayBuffer)
    {
        const byteArray = new Uint8Array(arrayBuffer);

        const url = window.URL.createObjectURL(new Blob([byteArray]));

        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "file.pdf"); //or any other extension
        document.body.appendChild(link);
        link.click();
    }
};
Run Code Online (Sandbox Code Playgroud)

javascript buffer file xmlhttprequest binary-data

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

binary-data ×1

buffer ×1

file ×1

javascript ×1

xmlhttprequest ×1