代码之家  ›  专栏  ›  技术社区  ›  yusha uzumo

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

  •  0
  • yusha uzumo  · 技术社区  · 7 年前

    我正在使用NPM的请求包向使用meetor.js restivus包编写的RESTAPI发布文件缓冲区。发布到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转换回我使用/talking meter.js的缓冲服务器端? 请帮忙!

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   yusha uzumo    7 年前

    我找到了自己问题的答案。发布到API的my 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

    推荐文章