【问题标题】:node.js / expressjs simple file upload issuenode.js / expressjs 简单文件上传问题
【发布时间】:2013-11-04 02:37:54
【问题描述】:

我正在使用 expressjs 作为中间件在节点服务器上创建一个简单的文件上传器。到目前为止,服务器端看起来像:

app.post('/upload', function(req, res) {
    console.log(req.files);

    //Handle the file
    fs.readFile(req.files.imageUploader.path, function(err, data) {
        var newPath = __dirname;
        console.log(newPath);
        console.log(data);
        fs.writeFile(newPath, data, function(err) {
            console.log(err);
            res.send("AOK");
        });
    });
});

现在,__dirname 的日志语句是我的源目录,正如预期的那样 (C:\Development\GitHub\ExpressFileUpload),但是上传时发生错误:

{ [Error: EISDIR, open 'C:\Development\GitHub\ExpressFileUpload']
errno: 28,
code: 'EISDIR',
path: 'C:\\Development\\GitHub\\ExpressFileUpload' }

我尝试将newPath 更改为/./,但没有变化,出现不同的错误,但仍然有错误。这与错误中path 中的双\\ 有关吗?我在这里错过了一些简单的东西吗?感谢您的帮助,如果需要更多信息,请告诉我。

【问题讨论】:

    标签: node.js upload express


    【解决方案1】:

    __dirname 全局对象是一个目录,而不是一个文件。因此,您无法打开它进行写作,这是fs.writeFile() 在您的脚本中尝试执行的操作,因此您获得了EISDIR。假设您希望使用与上传文件相同的名称写入文件,您可以这样做:

    var file = req.files.imageUploader;
    fs.readFile(file.path, function(err, data) {
      var path = __dirname + '/' + file.name;
      fs.writeFile(path, data, function(err) {
      });
    });
    

    【讨论】:

    • 同样的事情,除了现在我的console.log(data) 语句在读取数据并列出块之前读取undefined
    • 忽略我的原始答案,该信息被应用于您代码的错误部分。
    • 是的,就是这样!谢谢您的帮助! (55 秒,记错了,现在给 +1)
    猜你喜欢
    • 2014-11-30
    • 2017-06-17
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多