我正在尝试按照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
. 所以我在这里有点难过。想法?