Node.js中的POST缓冲区数据
问题描述:
我有兴趣将映像数据(存储在Amazon S3上)发布到REST端点。图像数据看起来是返回缓冲区:Node.js中的POST缓冲区数据
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)
答
我最终解决了这个问题,转移到'restler'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
})
});
我不认为这是由请求模块的支持。您可能想尝试使用内置http模块来发送它。 – igelineau