我正在尝试使用强大的上传文件,下面的教程在Node Beginner Book。在这段代码之后,我有一个服务器模块,它将request
对象传递给requestHandler模块。主页面加载具有以下处理程序的表单:
function start(response) {
console.log("Request handler 'start' was called.");
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>';
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.end();
}
提交表单时,/upload路径触发以下上传处理程序函数:
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");
console.log(util.inspect({error: error, fields: fields, files: files}));
fs.rename(files.upload.path, "/tmp/test.png", function(error) {
if (error) {
console.log(error);
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' />");
reponse.end();
});
}
但是,当单击上载按钮时,服务器崩溃并出现以下错误:
/home/****/Coding/nodebeginner/requestHandlers.js:38
fs.rename(files.upload.path, "/tmp/test.png", function(erro
^
TypeError: Cannot read property 'path' of undefined
at /home/****/Coding/nodebeginner/requestHandlers.js:38:25
at IncomingForm.<anonymous> (/home/****/Coding/nodebeginner/node_modules/formidable/lib/incoming_form.js:104:9)
at IncomingForm.EventEmitter.emit (events.js:92:17)
at IncomingForm._maybeEnd (/home/****/Coding/nodebeginner/node_modules/formidable/lib/incoming_form.js:551:8)
at Object.end (/home/****/Coding/nodebeginner/node_modules/formidable/lib/incoming_form.js:238:12)
at IncomingMessage.<anonymous> (/home/****/Coding/nodebeginner/node_modules/formidable/lib/incoming_form.js:129:30)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
所以显然files
变量是未定义的。我想可能有一个错误,但没有error
变量被设置为null
。所以我有点困惑。想法?
6条答案
按热度按时间vaqhlq811#
我也有同样的问题。表单标记的enctype属性缺少一个右双引号(“)。
l0oc07j22#
我也有同样的问题。我想你可以在Node Beginner Book的最后看到这些代码。我通过删除server.js文件中的以下代码修复了它:
route(handle,path,res,req);
daupos2t3#
我被同一个问题卡住了。听起来像上传类已被替换或拼写错误。尝试将引用从files.upload.path更改为files.upload.path。它在这里工作。查看master分支以获取更多信息:Git
o2g1uqev4#
看起来你的“var body”中有一些错误。尝试:
s5a0g9ez5#
form. parse中回调的参数名称有错误。
Node Beginner Book将代码显示为:
回调函数中的参数不应为复数:
查看/node_modlues/offensive/lib/incoming_form. js中的IncomingForm.prototype.parse。回调正在侦听单数的“field”和“file”。
8ljdwjyq6#
这是一个老问题,但如果有人在2023年仍然遇到这个问题,请在下面尝试。