为什么我可以使用绝对路径将具有Formidable的文件上载到文件夹但不是相对的?

时间:2015-04-06 18:02:57

标签: node.js file-upload relative-path absolute-path formidable

像许多其他新手一样,我正在跟随曼努埃尔·基斯林的“The Node Beginner Book”。

我们应该通过Formidable模块启用图片上传,不断将图像重命名为“test.png”并显示它。

本书使用路径/tmp/test.png,一切正常。但这不是一个相对路径,我的图像实际上保存在Linux的tmp文件夹中!

我在我的项目中创建了文件夹“tmp”,并尝试在那里发生同样的事情,但我只是显示错误!

ENOENT, open './tmp/test.png'

当我尝试路径tmp/test.png时会发生同样的事情,但有趣的是,当我将实际图像直接放入tmp文件夹并将其显示在我的页面上时,这两个路径都有效。所以语义/语法没有问题,或者......?

我的requestHandler.js,重要的部分是上传和显示功能:

var querystring = require("querystring"),
fs = require("fs"),
formidable = require("formidable");

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();

}

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");

    fs.rename(files.upload.path, "./tmp/test.png", function(err) {
        if (err) {
            console.log("Error Flynn");
            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' />");
    response.end();
});
}

function show(response) {
  console.log("Request handler 'show' was called.");
  fs.readFile("./tmp/test.png", "binary", function(error, file) {
    if(error) {
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(error + "\n");
        response.end();
    }
    else {
        response.writeHead(200, {"Content-Type": "image/png"});
        response.write(file, "binary");
        response.end();
    }
  });
}

exports.start = start;
exports.upload = upload;
exports.show = show;

值得注意的是,我专门用来解决 的“错误Flynn”错误消息被调用并且我放在文件夹中的文件被删除了!

这是日志:

Request for /upload received.
About to route a request for /upload
Request handler 'upload' was called.
about to parse
parsing done
Error Flynn
fs: missing callback Error: ENOENT, unlink './tmp/test.png'
fs: missing callback Error: EXDEV, rename '/tmp/upload_9bcb8afa8cd2f78ff52c294edd106965'
Request for /show received.
About to route a request for /show
Request handler 'show' was called.

1 个答案:

答案 0 :(得分:1)

相对路径有效,但它们相对于process.cwd(),而不是当前正在执行的模块。

__dirname引用了当前的.js文件