Node.js TypeError: Cannot read property 'path&

2019-08-03 16:54发布

问题:

I've looked at a lot of answer for this same question, but I haven't found a working solution yet. I am trying to make a web app that you can upload files to using express and multer, and I am having a problem that no files are being uploaded and req.file is always undefined.

Express and multer version as: "express": "^4.15.4", "multer": "^1.3.0"

My configure.js looks this:

multer = require('multer');

module.exports = function(app) {
app.use(morgan('dev'));
app.use(multer({
    dest: path.join(__dirname, 'public/upload/temp')}).single('file'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));

Consuming code looks like this:

    var tempPath = req.file.path,
        ext = path.extname(req.file.name).toLowerCase(),
        targetPath = path.resolve('./public/upload/' + imgUrl + ext);

        if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
            fs.rename(tempPath, targetPath, function(err) {
                if (err) throw err;

                res.redirect('/images/' + imgUrl);
            });
        } else {
            fs.unlink(tempPath, function() {
                if (err) throw err;

                res.json(500, {error: 'Only image files are allowed.'});
            });
        }

The form looks like this:

    <form method="post" action="/images" enctype="multipart/form-
data">
<div class="panel-body form-horizontal">
    <div class="form-group col-md-12">
        <label class="col-sm-2 control-label"
        for="file">Browse:</label>
        <div class="col-md-10">
            <input class="form-control" type="file"
            name="file" id="file">
        </div>
    </div>

回答1:

I have encountered the same problem. But then I change the multer version back to 0.1.8. Everything works fine. You may need to alter the package.json file: "multer": "^0.1.8"



回答2:

I bet your error message is on this line

    var tempPath = req.file.path,

because it's the only time you ask for "path" as a property of an object. Your problem seems pretty clear, you have no file in your request (AKA the object called "req"). You should log or inspect the object called req when in your consuming code to make sure you have a file within the request.