【问题标题】:nodejs throwing ENOENT error on file uploadnodejs在文件上传时抛出ENOENT错误
【发布时间】:2015-07-28 10:32:20
【问题描述】:

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

{ [Error: ENOENT, open '/uploads/lol.txt'] errno: -2, code: 'ENOENT', path: '/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>

【问题讨论】:

    标签: javascript node.js file-upload


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-26
      • 2018-11-26
      • 2020-12-04
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2018-12-25
      相关资源
      最近更新 更多