Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call multer middleware inside a controller in nodejs?

I'm trying to upload an image in my server. In the front-end I'm working with Angular. The front-end is working fine, I only posted to show you how I'm passing the file to back-end!

component.html

<div fxLayout="column" fxLayoutAlign="center center">
  <div>
    <mat-form-field>
      <ngx-mat-file-input placeholder="Only photos" [accept]="'.jpg, .jpeg, .png'" (change)="onChange($event)"></ngx-mat-file-input>
    </mat-form-field>
  </div>
  <div>
    <button mat-button (click)="onSubmit()">Send</button>
  </div>
</div>

component.ts - functions

  imagem: File;

  constructor(private uploadService: UploadService) { }

  onChange(event) {
    this.imagem = event.target.files[0];
  }
  onSubmit() {
    this.uploadService.upload(this.imagem);
  }

upload.service.ts - functions

  constructor(private http: HttpClient) { }

  upload(file: File) {
    const formData = new FormData();
    formData.append('img', file, file.name);
    this.http.post(environment.apiBaseUrl + '/upload', formData, {responseType: 'text'}).subscribe(
      res => console.log('Done')
    );
  }

In the back-end I have this structure:

app.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const rtsIndex = require('./routes/index.router');

var app = express();

// middleware
app.use(bodyParser.json());
app.use(cors());
app.use('/api', rtsIndex);

// start server
app.listen(3000, () => console.log('Port: 3000'));

index.router.js

const express = require('express');
const router = express.Router();

const ctrlUpload = require('../controllers/upload.controller');

router.post('/upload', ctrlUpload.send);

module.exports = router;

upload.controller.js

const express = require('express');
const multer = require('multer');

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/');
    },
    filename: (req, file, cb) => {
        cb(null, Date.now()+'-'+file.originalname);
    }
});

const upload = multer({ storage });

module.exports.send = (req, res) => {
  upload.single('img');
  console.log(req.body, req.files);
  res.send('ok');
}

I've tried to call the middleware inside the routing, but I don't think it's correctly and I didn't reach the goal. Algo, the upload is not one. On server side I get: {} undefined as result, which probably means the multer is not treating the file. On client side I get: Done.

So what am I doing wrong? And how can I make it works with this back end structure?

like image 631
Diego de Lima Avatar asked Dec 04 '22 18:12

Diego de Lima


2 Answers

Express middlewares are designed to be installed at the routing level. Indeed, in the MVC model express programmers call controllers "routes" (personally I perefer to call them controllers instead of routes in my code). Separating controllers from routes (they both mean the same thing) doesn't really make sense when viewed from traditional MVC frameworks - but you can if you want.

To use multer as designed you need to do it in index.router.js:

index.router.js

const express = require('express');
const router = express.Router();
const multer = require('multer');

const ctrlUpload = require('../controllers/upload.controller');

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/');
    },
    filename: (req, file, cb) => {
        cb(null, Date.now()+'-'+file.originalname);
    }
});

const upload = multer({ storage });

router.post('/upload', upload.single('img'), ctrlUpload.send);

module.exports = router;

Then you need to remove all the multer related code from upload.controller.js


You can however insist on doing it in upload.controller.js. The key here is to understand what middlewares are.

In Express, a middleware is a function with the prototype:

function (req, res, next) { // next is optional
    // middleware logic
}

Yes, that's right. The code in your upload.controller.js file is a middleware. You are writing a middleware yourself that happens to be at the end of the middleware chain.

You see, Express only accepts middlewares. Express has nothing else. Routes are middlewares that happen to be at the end.

Express .use(), .get(), .post() and related methods accept an infinite number of arguments. The first is optionally a route specifier (but not necessary) and the rest of the arguments are middlewares. For example:

app.get('/foo',
  (req, res, next) => {
    // first middleware
    next(); // next is what allows processing to continue
  },
  (req, res, next) => {
    // second middleware
    next();
  },
  (req, res, next) => {
    res.send('hello'); // controller logic - a controller
                       // is just the last middleware

    // Note: if you call next() instead of res.send() in a 
    // controller express will respond with a 500 internal 
    // server error status with whatever string you pass
    // to next() as the error message.
  }
);

Knowing this, we know what the function upload.single('img') returns. The function does not execute the middleware logic. Instead it returns the middleware function:

let middleware = upload.single('img');

// middleware is now a function with the prototype:
// (req, res, next) => {}

So to execute the middleware logic we have to call it (express would automatically call it as part of route processing, just like how it calls your controller function, but if we want to do it ourselves we can).

Here's what you need to do if you want to implement the middleware in upload.controller.js:

module.exports.send = (req, res, next) => {
  upload.single('img')(req, res, () => {
      // Remember, the middleware will call it's next function
      // so we can inject our controller manually as the next()

      console.log(req.body, req.files);
      res.send('ok');
  });
}

That's a lot to unpack. We can make the code easier to understand if we refactor it a little:

let middleware = upload.single('img');

module.exports.send = (req, res, next) => {
  // Define the controller here to capture
  // req and res in a closure:
  let controller = () => {
      console.log(req.body, req.files);
      res.send('ok');
  };

  middleware(req, res, controller); // call the middleware with
                                    // our controller as callback
}

But this is very non-standard and would be highly unexpected to an experienced Express.js programmer. I wouldn't do this even though it's possible. It also tightly couple the middleware with your controller completely negating the very flexible nature of Express middleware configuration system.

like image 79
slebetman Avatar answered Jan 07 '23 05:01

slebetman


An example of a separated file of Multer Middleware based in the @slebetman answer

./middlewares/multer.js

const multer = require('multer')
const ErrorMessages = require('../constants/ErrorMessages')

function makeid (length) {
  var result = ''
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  var charactersLength = characters.length
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return result
}

const DIR = './uploads/'
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR)
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-')
    cb(null, makeid(16) + '_' + fileName)
  }
})
const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (file.mimetype === 'image/png' || file.mimetype === 'application/pdf') {
      cb(null, true)
    } else {
      cb(null, false)
      return cb(new Error('Only .png, .jpg, .mp4 and .jpeg format allowed!'))
    }
  }
})

module.exports.send = (req, res, next) => {
  return upload.single('file')(req, res, () => {
    // Remember, the middleware will call it's next function
    // so we can inject our controller manually as the next()

    if (!req.file) return res.json({ error: ErrorMessages.invalidFiletype })
    next()
  })
}

./routes.js

routes.post('/object', multer.send, ObjectController.createObject)

This avoids the status 500 for wrong filetype Hope that helps someone :D

like image 23
Emanuel Avatar answered Jan 07 '23 05:01

Emanuel