multa
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" />
</form>
-----Configer Multer -------
const multer = require("multer");
const path = require("path")
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'public/uploads')
},
filename(req, file, cb) {
console.log(path.extname, file.originalname)
cb(null, `${file.fieldname}-${Date.now()}-${Math.round(Math.random()*1E9)}${path.extname(file.originalname)}`)
}
})
const checkFileType = (file, cb) => {
const fileType = /jpg|jpeg|png/
const extname = fileType.test(path.extname(file.originalname).toLowerCase())
const mimetype = fileType.test(file.mimetype)
if (extname && mimetype) {
return cb(null, true)
} else {
cb(new Error("Only Image Support!"), false)
}
}
const upload = multer({
storage,
limits: {
fileSize: 5e+6
},
fileFilter(req,file,cb){
checkFileType(file,cb)
}
})
app.post('/', upload.single('fild-name'), (req, res) => {
res.send(`/${req.file.path}`)
})
//OR => For Error Handling
app.post('/', (req, res,next) => {
upload(req, res, async (err) => {
if (err) {
return next(new Error("Server Error"))
}
const filePath = req.file.path
console.log(req.body)
let { error } = productSchema.validate(req.body)
if (error) {
fs.unlink(root + "/" + filePath, (err) => {
if (err) {
return next(new Error("Server Error"))
}
})
return next(error)
}
let { name, price, size, image } = req.body
let document
try {
document = await ProductModel.create({
name,
price,
size,
image: filePath
})
} catch (err) {
return next(err)
}
res.status(201).json(document)
res.send({})
})
})
Rasel Hossain