在分析本教程(由 Manuel Kiessling 撰写)时,我在执行最后一个示例时遇到错误;此处描述了此错误的描述以及消除错误的步骤。
实际上,问题是——为什么这些行为能解决问题?
简而言之,问题的实质是:强大模块的parse()方法无法解析表单,字段和文件字段保持未定义。很明显问题应该出在表单定义的某个地方,因为它没有被解析,但解决方案是在一个完全不同的地方更改代码——他们从请求对象中删除了事件处理程序——所以对我来说是因果关系仍然不明显。我想弄清楚到底是什么阻止了 parse() 正常工作。
表单代码(位于 requestHandlers.js 文件中):
var body = '<html>' +
'<head>' +
'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
'</head>' +
'<body>' +
'<form action="/upload" enctype="multipart/form-data" method="post">' +
'<input type="file" name="upload" multiple="multiple">' +
'<input type="submit" value="Upload File">' +
'</form>' +
'</body>' +
'</html>';
然后像这样解析此表单:
function upload(response, request) {
console.log("Request handler 'upload' was called.");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
/* Возможна ошибка в Windows: попытка переименования уже существующего файла */
fs.rename(files.upload.path, "/tmp/test.png", function(err) {
if (err) {
fs.unlink("/tmp/test.png");
fs.rename(files.upload.path, "/tmp/test.png");
}
});
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
解决方案(server.js 文件):
而不是这些线
// req.setEncoding("utf8");
// req.addListener("data", function(postDataChunk) {
// postData += postDataChunk;
// });
// req.addListener("end", function() {
// route(handle, pathname, res, req);
// });
保持简单
route(handle, pathname, res, req);