Utilizing multer
for image uploads involves a specific configuration. Here is an example of how to set up multer:
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 });
If you wish to access the fileInfo
object in the following handler, you can do so like this:
import { upload } from "src/middlewares/imageUpload";
router.post('/imageUpload', upload.single("upload"), async (req, res) => {
// Retrieve the filename from req.fileInfo
const filename = req.fileInfo.filename;
});
In certain cases, storing variables between middleware and handlers may be necessary. While some suggest using res.local
, it's important to note that multer's diskStorage configuration does not support the use of the res
parameter directly. Attempts to store the fileInfo
object in the req
sometimes yield inconsistent results, with req.fileInfo
being undefined on certain routes despite identical code.
How can one effectively pass the fileInfo
object to the subsequent handler?