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

时间:2018-07-23 10:45:45

标签: node.js meteor request gridfs-stream restivus

我正在使用npm的request包对使用meteor.js restivus包编写的REST api进行文件缓冲区发布。我发布到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); }); });

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

如果除了将文件作为编码字符串传递之外别无选择,那么是否有办法将编码的blob转换回我正在使用/交谈meteor.js的缓冲服务器端? 请帮忙!

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

1 个答案:

答案 0 :(得分:0)

我找到了自己问题的答案。我发布到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编码的文件的输出,但是当您在代码中的任何地方引用/使用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