使用Express-fileupload - Node.js上载文件时没有此类文件或目录错误

时间:2018-04-11 23:39:21

标签: javascript html node.js express ejs

我目前正在尝试上传pdf文件,将此文件存储在我可以查询的名称下的目录中,并将此名称存储在SQL表中。我正在使用Express-fileupload,我正在获取该文件,但是当我尝试使用.mv移动文件时出现Error: ENOENT: no such file or directory, open '/public/files/CLPs/minor_CLP.pdf'错误。这是我的帖子功能的代码:

app.post('/uploadCLP', isLoggedIn, function(req, res) {
    var communityID = req.user.communityID;

    console.log(req.files);

    var clpFile = req.files.clpFile;
    var clpName = communityID + "_CLP.pdf";

    clpFile.mv('/public/files/CLPs/' + clpName, function(err) {
        if(err)
            return console.log(err);
    });

    var updateQuery = ("UPDATE Community SET clpFile = ? WHERE communityID = ?");
    connection.query(updateQuery, [clpName, communityID], function(err, rows) {
        if(err) throw err;
        res.redirect(302, '/proposal');
    });
});

以下是我的EJS文件中调用该函数的表单:

<div class="well">
    <form action="/uploadCLP" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label>Community Learning Plan</label>
            <p>Only upload Community Learning Plans in PDF format.</p>
            <input type="file" accept=".pdf" class="form-control" name="clpFile">
        </div>
</div>

编辑以显示我的server.js文件:

// server.js

// get all the tools we need
var express  = require('express');
var session  = require('express-session');
var favicon = require('express-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');

var upload = require('express-fileupload');
var app      = express();
var port     = process.env.PORT || 1848;

var passport = require('passport');
var flash    = require('connect-flash');


require('./config/passport')(passport); // pass passport for configuration

app.use('/public', express.static('public'));

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.set('view engine', 'ejs'); // set up ejs for templating
app.use(upload());

// required for passport
app.use(session({
    secret: 'vidyapathaisalwaysrunning',
    resave: true,
    saveUninitialized: true
 } )); // session secret

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session


require('./app/routes.js')(app, passport); 

app.listen(port);
console.log('Server running on port ' + port);

此外,您可以在此处查看我的项目目录:

enter image description here

我不确定问题是我如何设置要保存的文件的目录,或者问题是我试图以不同的名称保存文件。任何帮助或提示将不胜感激! :)

1 个答案:

答案 0 :(得分:1)

由于路径在开头使用/,它会搜索该文件夹的根路径,而该路径不是项目的文件夹本身。

因为脚本位于项目的根文件夹中,所以正确的路径应为'public/files/CLPs/'