我正在编写一段代码,让客户端在服务器上上传两个文件。由于我使用了director路由器,所以我设置了一个这样的监听器:
request.chunks = [];
request.on('data', function (chunk) {
request.chunks.push( chunk.toString());
};
这是客户端上传文件时 block 的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
变量上的每个文件名和每个文件内容,但是浏览器有不同的倾向(对于这些边界,例如 google chrome 是这样的:'------WebKit...'),我想知道是否有一种直接的方法来解析文件名和文件内容(显然是来自 request.chunks
而不是 request
)一些模块,如强大的、多部分的或查询字符串?
感谢@micnic,我想出了一个 header 解析器。它可能需要修改,这在这个级别是受欢迎的:
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;
}
最佳答案
对于我的模块 simpleS我写了一个解析器: https://github.com/micnic/simpleS/blob/ccc8e600013da70d5204c1b66149e834d2c0fea2/utils/utils.js#L365
可能理解起来有点困难,但它确实有效。
“...我想知道是否有一种直接的方法可以使用某些模块(例如 formidable 或 multi-part 或 querystring)来解析文件名和文件内容?...”,您阅读了 formidable 的文档吗?
从那里:
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}));
});
/* ... */
关于node.js - 如何在nodejs中处理http请求中的表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16685895/