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?