发送 ArrayBuffer 或 Blob 并重建它们的正确方法是什么?

What is the correct way to send ArrayBuffer or Blob across and reconstruct them?

在将数据发送到客户端之前,我已经阅读了很多关于如何在 ArrayBufferBlobUint8Array 之间进行转换的帖子......但是我似乎根本无法让它工作。当我确实获得数据时,在将它们输出到文件之前,我无法将它们重建为 Blob..

const Blob = require('cross-blob');
const randomBytes = require('randombytes');

const buffer = randomBytes(1024); // Supposed to give me Buffer

以下是我试过的东西...

data = buffer;

^ 给我 <Buffer 11 22 33 ...>

data = Uint8Array.from(buffer); 

^给我一个整数数组,这个看起来最有希望?但是当到达客户端时,它变成了一个带有索引和字节值的对象...

data = Uint8Array.from(buffer).buffer;

^ 给出 ArrayBuffer { byteLength: 1024},检查时显示 size: 2type: 'text/plain'...

data = new Blob(buffer, { type: 'application/octet-stream' });
data = new Blob([new Uint8Array(buffer, buffer.byteOffset, buffer.length)], { type: 'application/octet-stream' });
data = new Blob([Uint8Array.from(buffer)], { type: 'application/octet-stream' });

^ 所有这些,当到达客户端时还带有 size: 2type: 'text/plain'...

服务器端,我是运行快递:

router.get('/test/*', function(req, res, next) {
  ...
  let data = myFunctionThatGeneratesData();
  res.send(data);

});

在客户端,我这样请求 (Angular/TypeScript):

this.http.get('/test/random-bytes-array', {
  responseType: 'blob'  // also tried 'arraybuffer'
}).subscribe(data => {
  debugger;
  console.log(data);
});

我一定是做错了什么...我正在尝试发送多个二进制数据块,作为 ArrayBufferUint8ArrayBlob(无论有效)当到达另一端时,将它们组合回 Blob.

在Node.js、crypto.randomBytes returns a Buffer。这是用于将原始数据发送到客户端的正确类型。

使用 Express 时,使用 res.type(). However, when sending a Buffer, if the content-type header is not set in any other middleware, then express will use application/octet-stream by default 设置正确的响应内容类型很重要。

When the parameter is a Buffer object, the method sets the Content-Type response header field to "application/octet-stream", unless previously defined.

router.get('/test/*', function(req, res, next) {
  ...
  let data = myFunctionThatGeneratesData();
  res.type('application/octet-stream').send(data);
  // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ might not be necessary
});

最后在 Angular 中,使用 responseType: 'blob' 是正确的:

this.http.get('/test/random-bytes-array', {
  responseType: 'blob'
}).subscribe(data => {
  console.log(data);
});