gpt4 book ai didi

node.js - 为什么我可以使用绝对路径而不是相对路径将 Formidable 文件上传到文件夹?

转载 作者:太空宇宙 更新时间:2023-11-04 00:56:40 25 4
gpt4 key购买 nike

像许多其他新手一样,我正在阅读 Manuel Kiessling 所著的《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;

值得注意的是,我专门放在那里进行故障排除的“Error 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.

最佳答案

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

__dirname 正在引用当前的 .js 文件

关于node.js - 为什么我可以使用绝对路径而不是相对路径将 Formidable 文件上传到文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29476801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com