Reputation: 3835
This is my server.js file. I am trying to write a fileupload using native nodejs (without lib). Everytime i try to upload a file, it throws me a weird error. This is a Linux machine.
{ [Error: ENOENT, open '/uploads/lol.txt'] errno: -2, code: 'ENOENT', path: '/uploads/lol.txt' }
/uploads/lol.txt is the destination path. Needs serious help.
var http = require('http'),
fs = require('fs');
//qs = require('querystring');
var port = 9000, server, data;
data = fs.readFileSync('index.html');
server = http.createServer(function(req , res) {
switch(req.url) {
case "/":
__serverResponse(res);
break;
case "/upload":
__handleUpload(req, res);
break;
default:
__serverResponse(res);
break;
}
});
function __handleUpload(req, res) {
var __bufferData = __contentLength = 0;
req.on('data', function(chunk) {
__bufferData += chunk;
});
req.on('end', function() {
//write contents to a file
fs.writeFile('/uploads/lol.txt', __bufferData, function(err) {
if (err)
return console.log(err);
});
//end response with 200 OK
//Modularize __serverResponse code
res.end();
});
}
function __serverResponse(res) {
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
res.write(data);
res.end();
}
function startServer() {
server.listen(port, function() {
console.log('Server listening at port '+ port);
});
}
function closeServer() {
server.close();
}
module.exports = {
start: startServer,
end: closeServer
};
This is the HTML file:
<!DOCTYPE html>
<html>
<head>
<title>File Upload program</title>
</head>
<body>
<form id="simple-form" action='/upload' method='POST'>
<label for='file-input'> Select file </label>
<input type='file' id='file-input' name='file-name'/>
<input type='submit'/>
</form>
</body>
</html>
Upvotes: 1
Views: 1994
Reputation: 4182
/uploads/lol.txt
is an absolute file path. Try just using uploads/lol.txt
to make it relative to the root directory of your application.
Upvotes: 3