Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling when uploading file using multer with expressjs

I am using multer to save the file on server developed through express & nodejs.

I am usign following code.

var express = require('express'),
    multer  = require('multer')

var app = express()

app.get('/', function(req, res){
  res.send('hello world');
});

app.post('/upload',[ multer({ dest: './uploads/'}), function(req, res){

    res.status(204).end()
}]);

app.listen(3000);

Multer saves the file for me in the specified destination folder.

All this is working fine but I have following questions:

  1. If the file saving fails for various reasons, it looks like my route will always return status 204.
  2. I am not sure if status 204 is retured after file is saved or while the file is getting saved asynchronously, status 204 is returned.
like image 534
SharpCoder Avatar asked Jun 15 '15 06:06

SharpCoder


People also ask

How do you catch errors in multer?

Error handling If you want to catch errors specifically from Multer, you can call the middleware function by yourself. Also, if you want to catch only the Multer errors, you can use the MulterError class that is attached to the multer object itself (e.g. err instanceof multer. MulterError ).

Can we use multer without Express?

You cannot use Multer without because it's Express middleware. It's based on Busboy so you can check how it uses it and use it directly.

How do I upload files to Express?

Open the local page http://127.0.0.1:2000/ to upload the images. Select an image to upload and click on "Upload Image" button. Here, you see that file is uploaded successfully. You can see the uploaded file in the "Uploads" folder.


1 Answers

This is how to write multer middleware that handle upload and errors

const multer = require("multer");

function uploadFile(req, res, next) {
    const upload = multer().single('yourFileNameHere');

    upload(req, res, function (err) {
        if (err instanceof multer.MulterError) {
            // A Multer error occurred when uploading.
        } else if (err) {
            // An unknown error occurred when uploading.
        }
        // Everything went fine. 
        next()
    })
}
like image 96
Raad Altaie Avatar answered Sep 19 '22 12:09

Raad Altaie