0

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?

glinda93
  • 7,659
  • 5
  • 40
  • 78

1 Answers1

2

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.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • So, in other words, if `req.fileInfo` is undefined, that means multer didn't upload any files? – glinda93 May 18 '20 at 20:38
  • `req.fileInfo` will contain the info about the uploaded file, right? So if multer hasn't uploaded any file, what will `req.fileInfo` contain? In short, code in your multer configuration will execute only if there's a file to be uploaded – Yousaf May 18 '20 at 20:41
  • I passed an array to form data in frontend. Changed it to file object and it worked. Thanks! – glinda93 May 18 '20 at 21:03