Search code examples
javascripttypescriptexpressmiddlewaremulter

multer: how to pass variables to next handler


I'm using multer to upload images. The following is my multer configuration:

import multer from "multer";
import * as mime from "mime-types";
import path from "path";

export const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req: any, file, cb) {
    const name = path.parse(file.originalname).name + "_" + Date.now();
    const extension = mime.extension(file.mimetype);
    const filename = `${name}.${extension}`;
    /**
    req.fileInfo = {
      filename,
      name,
      extension
    } */
    cb(null, filename);
  },
});
export const upload = multer({ storage: storage });

I want to get fileInfo object in next handler.

import { upload } from "src/middlewares/imageUpload";

router.post('/imageUpload', upload.single("upload"), async (req, res) => {

//
const filename = req.fileInfo.filename;

});

According to this answer, res.local is the correct place to store variables between middleware and handlers.

But multer diskStorage configuration does not accept res parameter. I tried to store fileInfo object in req but sometimes it works and sometimes it doesn't(req.fileInfo is undefined for some routes, although the code is exactly the same).

How can I pass fileInfo to next handler?


Solution

  • multer middleware automatically sets the property named file on req object which contains the information about the uploaded file and can be accessed in the next middleware, so you don't need to set it your self.

    If you still want to do that, you can attach fileInfo object to req object but it will only be available in next handlers where multer middleware is one of the middlewares in the pipeline. So req.fileInfo will be undefined for routes for which request doesn't goes through multer middleware.

    You can make every request pass through the multer middleware but if that request doesn't contains any file that should be uploaded, req.fileInfo will be undefined because no file was uploaded by multer.