When user sends a multi part form with files/images selected, generally in Meteor or node.js, the server side POST url handler uses this.request or req or request object to detect whether its a POST method or any other and its headers etc but what I don't understand is, where is the actually file located at this request object and how do I retrieve it so that it can be used for image/file upload or certain manipulations at server?
当用户发送选择了文件/图像的多部分表单时,通常在Meteor或node.js中,服务器端POST url处理程序使用this.request或req或request对象来检测它是POST方法还是其他任何及其标题等但我不明白的是,实际文件位于此请求对象的哪个位置以及如何检索它以便它可用于图像/文件上载或服务器上的某些操作?
1 个解决方案
#1
node provides the querystring api to parse strings that look like:
node提供了查询字符串api来解析看起来像这样的字符串:
foo=bar&baz=qux&baz=quux&corge
...which is how multi part form data is also sent. Parsing this with that api will return an object:
...这也是多部分表格数据的发送方式。使用该api解析此将返回一个对象:
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
So, you can first detect the method of the request, and if it is POST
, you can attach a handler to 'data'
, get all the data into your own variable, and on 'end'
, parse it using querystring
:
因此,您可以首先检测请求的方法,如果是POST,您可以将处理程序附加到'data',将所有数据附加到您自己的变量中,并在'end'上使用查询字符串解析它:
var qs = require('querystring');
// your request callback function would be something like:
function (request,response){
if(request.method=='POST'){
var body = '';
request.on('data',function(data){
body += data;
//reject requests that have sent too much data (eg 2MB):
if(body.length > 2e6){
// Send HTTP status code for `Request Entity Too Large`:
response.writeHead(413);
response.end();
});
request.on('end', function(){
var form = qs.parse(body);
//use form as object
});
} // end if
} // end handler
#1
node provides the querystring api to parse strings that look like:
node提供了查询字符串api来解析看起来像这样的字符串:
foo=bar&baz=qux&baz=quux&corge
...which is how multi part form data is also sent. Parsing this with that api will return an object:
...这也是多部分表格数据的发送方式。使用该api解析此将返回一个对象:
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
So, you can first detect the method of the request, and if it is POST
, you can attach a handler to 'data'
, get all the data into your own variable, and on 'end'
, parse it using querystring
:
因此,您可以首先检测请求的方法,如果是POST,您可以将处理程序附加到'data',将所有数据附加到您自己的变量中,并在'end'上使用查询字符串解析它:
var qs = require('querystring');
// your request callback function would be something like:
function (request,response){
if(request.method=='POST'){
var body = '';
request.on('data',function(data){
body += data;
//reject requests that have sent too much data (eg 2MB):
if(body.length > 2e6){
// Send HTTP status code for `Request Entity Too Large`:
response.writeHead(413);
response.end();
});
request.on('end', function(){
var form = qs.parse(body);
//use form as object
});
} // end if
} // end handler