当 post 使用 nodejs/npm 的请求包时,我如何 post 普通文件缓冲区而不是二进制编码文件?

How do I post a plain file buffer instead of binary-encoded-file when posting with nodejs/npm's request package?

我正在使用 npm 的请求包对使用 meteor.js restivus 包编写的 REST api 文件缓冲区进行 post。 post 到 api 的 node.js 客户端代码如下:

    url = 'http://localhost:3000/api/v1/images/';

fs.readFile('./Statement.odt', function read(err, data) { if (err) { throw err; } console.log(data); //At this stage the file is still a buffer - which is correct var file = data; request.post({ uri: url, headers: { 'X-User-Id': userId, 'X-Auth-Token': authToken }, form: { file: file, //Inside the request.post the file is converted to binary encoding name:"Statement.odt" } }, function(err, httpResponse, body) { if (err) { return console.error('post failed:', err); } console.log('Get successful! Server responded with:', body); }); });

这里的problem/issue是在request.post里面把文件转换成二进制编码的blob。请参阅我在上面代码中 "request.post" 的第一个参数的 "form:" 属性 中的注释。这成为我的 meteor.js 服务器上的一个问题,该服务器需要文件作为缓冲区而不是二进制编码文件。 (有关信息:我正在使用 Ostr-io/files' GridFS 来存储文件 - 它需要文件作为缓冲区)

如果除了将文件作为编码字符串传递之外别无他法,那么有没有办法将该编码的 blob 转换回我所在的缓冲区服务器端 using/talking meteor.js? 请帮忙!

如果您需要更多信息,请告诉我,我会提供。

我找到了我自己问题的答案。发布到 api 的我的 node.js 客户端代码更改如下:

 url = 'http://localhost:3000/api/v1/images/';
 fs.readFile('./Statement.odt', function read(err, data) {
  if (err) {
   throw err;
  }
  console.log(data);
  //var file = new Buffer(data).toString('base64');
  var file = data;
  //var file = fs.readFileSync('./Statement.odt',{ encoding: 'base64' });
  
  var req = request.post({
    uri: url, 
    headers:  {
   'X-User-Id': userId,
   'X-Auth-Token': authToken
    },
    /*form: { //Post to the body instead of the form
     file: file,
     name:"Statement.odt",
    },*/
    body: file, //Post to the body instead of the form
    json:true  //Set json to true
    //encoding: null
  }, function(err, httpResponse, body) {
    if (err) {
   return console.error('post failed:', err);
    }
  
    console.log('Get successful!  Server responded with:', body);
  });
 });

在服务器端按如下方式访问 json 数据并将文件转换回缓冲区:

var bufferOriginal = Buffer.from(this.request.body.data)

请注意,当您执行 console.log(bufferOriginal) 时,您会得到以 utf8 编码的文件输出,但是当您在代码中的任何地方执行 reference/use bufferOriginal 时,它被识别为一个文件缓冲区,看起来有人喜欢:

<Buffer 50 4b 03 04 14 00 00 08 00 00 00 55 f6 4c 5e c6 32 0c 27 00 00 00 27 00 00 00 08 00 00 00 6d 69 6d 65 74 79 70 65 61 70 70 6c 69 63 61 74 69 6f 6e 2f ... >

感谢@Dr.Dimitru 将我推向解决方案的方向并指出 this.request.body 已经是 json