express multer Cannot read property 'profileim

2019-07-03 22:08发布

I am trying to submit a form which has a file input within it with a name of profileimage, i am using express 4, express generator and multer.

In my app.js I added multer like so:

var multer = require('multer');
var upload = multer({ dest: './uploads' });

The tutorial i am following actually sets up multer like so (after requiring it) but it gives me an error:

app.use(multer({dest: './uploads'}));

And in my routes folder inside the respective file I have the following:

router.post('/register', function(req, res, next) {
// get form values
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;

// check for image field
if (req.files.profileimage)
{
    console.log('Uploading file...');
...

However when I submit the form I get the following error:

Cannot read property 'profileimage' of undefined

It seems to not be able to understand req.files.profileimage, but I don't know why?

2条回答
时光不老,我们不散
2楼-- · 2019-07-03 22:24

The API for multer changed a bit some time ago, so some tutorials out there still use the old API.

For a single file, you would do something like:

var uploads = multer({dest: './uploads'});

// ...

router.post('/register', uploads.single('profileimg'), function(req, res, next) {

   // ...

   if (req.file) {
     console.log('Profile image uploaded');
   }
});

See the multer documentation for more examples of other scenarios.

查看更多
祖国的老花朵
3楼-- · 2019-07-03 22:34
if (req.files && req.files.profileImage) {
// only if there are files
} else {
 // You should see this now
}
查看更多
登录 后发表回答