Node.js中的POST缓冲区数据

时间:2015-05-27 18:43:25

标签: node.js rest request buffer

我有兴趣将图像数据(存储在Amazon S3上)发布到REST端点。图像数据似乎作为缓冲区返回:

var request = require('request');
var s3 = new AWS.S3();

s3.getObject({Bucket: bucket, Key: key}, function(err, data) {
  console.log(data.Body);
  // <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 ...

当我尝试使用请求库上传缓冲区时:

  request.post('https://example.com', {'upload_file': data.Body});

它爆炸,因为它显然试图对URI进行编码:

/node_modules/request/node_modules/qs/lib/stringify.js:40
        return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)];
                                                   ^
URIError: URI malformed
    at encodeURIComponent (native)
    at Object.internals.stringify (/node_modules/request/node_modules/qs/lib/stringify.js:40:52)
    at Object.module.exports [as stringify] (/node_modules/request/node_modules/qs/lib/stringify.js:93:38)
    at Request.form (/node_modules/request/request.js:1320:20)
    at Request.init (/node_modules/request/request.js:503:10)
    at new Request (/node_modules/request/request.js:272:8)
    at request (/node_modules/request/index.js:56:10)

1 个答案:

答案 0 :(得分:0)

我最终通过搬到“餐馆”来解决这个问题。 NPM包和使用(遗憾)未记录的功能。以下是:

request.post('https://example.com', {'upload_file': data.Body});

变成了:

s3.getObject({Bucket: bucket, Key: key}, function(err, data) {
  var form = {
    file_name: key,
    upload_file: rest.data(key, data.ContentType, data.Body)
  };
  var opts = {
    data: form,
    multipart: true
  };  
  rest.post('example.com', opts).on('complete', function(results, response) {
    //...handle success
  })
});