我正在编写代码让客户端在服务器上上传两个文件。由于我使用了导演路由器,我设置了一个这样的监听器:
request.chunks = [];
request.on('data', function (chunk) {
request.chunks.push( chunk.toString());
};
这是客户端上传文件时(基于浏览器边界更改)的块的console.log:
-----------------------------7dd2c419180232
Content-Disposition: form-data; name="filename"
-----------------------------7dd2c419180232
Content-Disposition: form-data; name="uploadfile"; filename="first.txt"
Content-Type: application/octet-stream
the content of first file
-----------------------------7dd2c419180232
Content-Disposition: form-data; name="wfilename"
-----------------------------7dd2c419180232
Content-Disposition: form-data; name="wuploadfile"; filename="second.txt"
Content-Type: application/octet-stream
the content of the second file
-----------------------------7dd2c419180232--
我通过几个正则表达式处理问题,用于提取request.chunks
变量上的每个文件名和每个文件内容,但浏览器具有不同的趋势(对于这些边界,例如谷歌浏览器是像这样:'------ WebKit ...')我想知道是否有直接的方法来解析文件名和文件内容(显然来自request.chunks
而不是request
)一些模块如强大或多部分或查询字符串?
感谢@micnic,我想出了一个头文件的解析器。它可能需要在这个级别受欢迎的修订:
exports.parseMultipart = function(request) {
// Convert the chunks to string
var str = request.chunks.toString();
// Get the boundry out pf header
var boundry = '--' + request.headers["content-type"].substring(request.headers["content-type"].indexOf('=')+1, request.headers["content-type"].length);
// Initialization
var request_data = {};
index = 0;
// For each form element, store the value in request_data
while (str.indexOf(boundry, index) != -1) {
index += boundry.length;
i = str.indexOf(" name=\"",index);
j = str.indexOf("\"",i+7);
name = str.substring(i+7,j);
var value = {};
if (str.charAt(j+1)==';') {
value["type"] = "file";
i = j + 3;
j = str.indexOf("\"",i+14);
filename = str.substring(i+10, j);
value["filename"] = filename;
i = j + 17;
j = str.indexOf("\r", i);
contentType = str.substring(i, j);
value["content-type"] = contentType;
i = j + 4;
j = str.indexOf("\n\r\n" + boundry, i);
fileContent = str.substring(i, j);
value["content"] = fileContent;
} else {
value["type"] = "field";
i = j + 5;
j = str.indexOf("\r\n" + boundry,i);
value["content"] = str.substring(i,j);
}
index = str.indexOf(boundry, index) + 2;
request_data[name] = value;
}
return request_data;
}
答案 0 :(得分:0)
对于我的模块simpleS,我写了一个解析器: https://github.com/micnic/simpleS/blob/ccc8e600013da70d5204c1b66149e834d2c0fea2/utils/utils.js#L365
可能有点难以理解,但它确实有效。
“...我想知道是否有直接的方法来解析文件名和文件内容与某些模块,如强大或多部分或查询字符串?...”,你读过强大的文档吗?
从那里:
var formidable = require('formidable');
/* ... */
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
/* ... */