nodejs在文件上传时抛出ENOENT错误

时间:2015-07-28 01:02:10

标签: javascript node.js file-upload

这是我的server.js文件。我试图使用本机nodejs(没有lib)编写文件上载。每次我尝试上传文件时,都会引发一个奇怪的错误。这是一台Linux机器。

{[错误:ENOENT,打开'/uploads/lol.txt']错误:-2,代码:'ENOENT',路径:'/ uploads/lol.txt'}

/uploads/lol.txt是目标路径。需要认真的帮助。

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>

1 个答案:

答案 0 :(得分:3)

/uploads/lol.txt是绝对文件路径。尝试使用uploads/lol.txt使其相对于应用程序的根目录。