I'm trying to upload a file using formidable, following the tutorial in the Node Beginner Book. Following this code, I have a server modules that passes the request
object to a requestHandler module. The main page loads a form with the following handler:
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();
}
When the form is submitted, the /upload path triggers the following upload handler function:
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();
});
}
When the upload button is clicked, however, the server crashes with the following error:
/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)
So evidently the files
variable is undefined. I thought there might be an error, but no the error
variable is set to null
. So I'm a bit stumped here. Ideas?