anshu_anand
anshu_anand

Reputation: 99

What do multer().single() returns?

I came across how to handle error of multer , but I am unble to understand its flow .

var multer = require('multer')
var upload = multer().single('avatar')
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err) {
  // An error occurred when uploading
  return
if (err instanceof multer.MulterError) {
  // A Multer error occurred when uploading.
} else {
  // An unknown error occurred when uploading.
}
// Everything went fine
// Everything went fine.
 })
 })

What I am unable to understand :-

What do multer().single() returns and how are we using that(upload function) inside the router handler as shown in code ?

EDIT :

I am unable to find the source code , what is wriiten inside multer for .single() function . Can anyone provide me link to it?

Edit 2

I have tried to handle error in the following way but it is not working . What's wrong with it ?

const storage = new gridfsStorage({
    url : 'mongodb://localhost:27017/uploadeditems' ,
    file : (req , file) => {
        if(file.mimetype === 'image/jpeg') {
            return {
                filename : file.originalname,
                bucketName : 'Images'
            }
        }
        else if(file.mimetype === 'application/pdf') {
            return {
                filename : file.originalname , 
                bucketName : 'projectPDFs'
            }
        }

        else {
            return null
        }
    }
})


upload = multer({storage })


app.get('/' , (req , res) => {
    res.render('upload')
})

app.post('/upload' , upload.single('pproject')  , async (req, res) => {

    res.render('upload' , {
            msg : "File has been uploaded successfully"
        })
} ,

(err , req , res) => {
  res.json({
    msg : "Some error occured"})
)

I am assuming if some error occurs , upload.single() will call next(err) , which will be caught by the last error handler .

Upvotes: 1

Views: 5091

Answers (1)

jfriend00
jfriend00

Reputation: 707238

multer().single() returns a middleware function that expects to be called with the arguments (req, res, callback).

It can be called automatically as middleware as in:

app.post('/profile', multer().single('avatar'), (req, res) => {
     // access uploaded file in req.file
});

When used this way, the callback is the Express next argument.

Or, if you want more control over what happens when there's an error, then you can call it manually as shown in the code in your question where your own code sees the error rather than just diverting to the installed Express error handler.

Upvotes: 2

Related Questions