multer configuration with app.use returns TypeError

后端 未结 3 1584
时光说笑
时光说笑 2020-12-30 06:10

I\'m trying to configure multer in my app.js file (using node.js/express) in order to allow users to upload images. I have the following code in app.js:

//va         


        
相关标签:
3条回答
  • 2020-12-30 06:21

    Credit goes to @stdob-- for guiding me in the right direction. The multer documentation I was looking at seems to have been updated while I was working and therefore I was using the code incorrectly.

    Multer should be used with its middleware functions. Consequently the correct way to use this package is as follows:

    var multer = require('multer');
    
    var upload = multer({dest:'uploads/'});
    
    var cpUpload = upload.single('postImg');
    
    router.post('/createpost', cpUpload, function(req,res){
    
      console.log(req.file);
      res.redirect('/');
    
    }
    

    This code snippet will create a post route for '/createpost' and will upload a single document (by the form name 'postImg') to /uploads in the server. req.file contains the JSON with the file information (such as the file path). Keep in mind that this will not automatically get rid of the uploaded file.

    More information can be found here: https://www.npmjs.com/package/multer

    0 讨论(0)
  • 2020-12-30 06:26

    this will do

    app.use(multer({dest:'./public/images/uploads'}).any());
    
    0 讨论(0)
  • 2020-12-30 06:34

    Problem is that multer({dest:'./uploads/'}) return object, not middleware function. And if we look at the code module that we will see that there are three middlware functions:

    multer({dest:'./uploads/'}).single(...)
    multer({dest:'./uploads/'}).array(...)
    multer({dest:'./uploads/'}).fields(...)
    

    Try one of them.

    0 讨论(0)
提交回复
热议问题