Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Too Large Error Handling Nodejs Express Multer

I am using multer with ExpressJS. I want to limit file uploads to 0.5 MB.

var limits = { fileSize: 0.5 * 1024 * 1024 };

var upload = multer({ dest: './public/uploads/', limits: limits
 }).single('upl')

 app.post('/',upload, function (req, res) {
  upload(req, res, function (err) {
    if (err) {
            console.log("cs " + err);
      return
    }

           res.end('You new avatar is uploaded')
    // Everything went fine
  })
})

When the file is under 0.5 MB I can see 'You new avatar is uploaded' but when it is over I get,

Error: File too large
   at makeError (C:\Users\Owner\Desktop\nodejs projects\dummy\node_modules\multer\lib\make-error.js:12:13)
   at abortWithCode (C:\Users\Owner\Desktop\nodejs projects\dummy\node_modules\multer\lib\make-middleware.js:77:22)
   at FileStream.<anonymous> (C:\Users\Owner\Desktop\nodejs projects\dummy\node_modules\multer\lib\make-middleware.js:139:11)
   at emitNone (events.js:80:13)
   at FileStream.emit (events.js:179:7)
   at PartStream.onData (C:\Users\Owner\Desktop\nodejs projects\dummy\node_modules\busboy\lib\types\multipart.js:220:18)
   at emitOne (events.js:90:13)
   at PartStream.emit (events.js:182:7)
   at readableAddChunk (_stream_readable.js:153:18)
   at PartStream.Readable.push (_stream_readable.js:111:10)

Obviously I would never want the end user to see this. How can I handle this properly?

like image 657
sssaini Avatar asked May 18 '16 02:05

sssaini


1 Answers

try rewrite like this (remove "upload" first):

app.post('/', function (req, res) {
  upload(req, res, function (err) {
    if (err) {
        console.log("cs " + err);
      return
    }

    res.end('You new avatar is uploaded')
    // Everything went fine
  })
like image 74
KibGzr Avatar answered Sep 21 '22 14:09

KibGzr