------------ multer
const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
destination: path.join(__dirname, "../..", "public/uploads/"),
filename: function (req, file, cb) {
cb(null, "IMAGE-" + Date.now() + path.extname(file.originalname));
},
})
const multerMiddleware = multer({
storage: storage,
fileFilter: (req, file, cb) => {
let ext = path.extname(file.originalname);
if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") {
cb(new Error("File type is not supported"), false);
return;
}
cb(null, true);
},
limits: { fileSize: 90000000000000 },
}).single("myImage");
----------- route and controller
router.post('/', multerMiddleware, async (req, res) => {
const imagePath = req.file.path
})
IN REACT
return (
<input type="file" name="myImage"
onChange={(e) => {
const formData = new FormData();
formData.append('myImage', e.target.files[0]);
props.submitCategory(formData) // call api with body formData
}}
/>
)
0 Comments