【问题标题】:ENOENT Error - I'm successfully uploading files but can't move themENOENT 错误 - 我已成功上传文件但无法移动它们
【发布时间】:2014-07-22 02:29:55
【问题描述】:

我已成功将文件上传到临时目录,并希望将它们移动到目录profile_pictures。好像是这么简单的事情,我居然在这里卡了一个小时!

使用 Expressfs 的非常简单的代码:

app.post('/upload', function (req, res, next) {
    console.log("User uploading profile picture...");

    var tmp_path = req.files.profile_picture.path; // get the temporary location of the file
    var ext = path.extname(req.files.profile_picture.name); // get the extension of the file with the path module

    var target_path = '/profile_pictures/' + req.body.username + ext; // set where the file should actually exists - in this case it is in the "images" directory

    fs.rename(tmp_path, target_path, function (err) { // move the file from the temporary location to the intended location
        if (err) throw err;

        fs.unlink(tmp_path, function (err) { // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
            if (err) throw err;
            res.send('File uploaded to: ' + target_path + ' - ' + req.files.profile_picture.size + ' bytes');
        });
    });
});

但这会导致错误:

错误:ENOENT,重命名“tmp/5162-2fftn.jpg”] errno:34,代码:“ENOENT”,路径:“tmp/5162-2fftn.jpg”

上面的图片是我的 SFTP 管理器连接到这个应用程序的工作目录的屏幕截图,所以很明显该目录确实存在!

我的错误是什么?

【问题讨论】:

  • 尽管有错误,您仍在继续,如果有err,您不应该继续。此外,您的第二个回调未声明 err 参数,因此您不知道取消链接的错误是什么。
  • @Esailija 哦,我明白了。那么错误在fs.rename。我会修复错误处理
  • 你试过使用绝对路径吗?相对路径可能会认为根与您预期的不同
  • 我没试过,没有。我正在使用 linux 服务器; linux 路径的根部分是什么样的..?就像在 Windows 中一样,它是 C:\
  • 与操作系统无关,我的意思是当您将./tmp 之类的相对路径传递给fs.rename 时,它会自行计算出绝对路径,这可能不是正确的路径。试试像"/var/www/node/tmp/file.jpg" 这样的绝对路径。

标签: javascript node.js express fs


【解决方案1】:

我自己花了好几个小时来解决这个问题。看看here以获得澄清, https://github.com/nodejs/node-v0.x-archive/issues/2703

这里的线程实际上为我指明了正确的方向, Move File in ExpressJS/NodeJS

是的,fs.rename 不会在两个不同的磁盘/分区之间移动文件。这是正确的行为。 fs.rename 提供与 linux 中的 rename(2) 相同的功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多