Files
backend-Eprocurement/middlewares/multer/singlefinance.js
2025-12-05 06:21:42 +07:00

74 lines
2.6 KiB
JavaScript

const multer = require('multer');
const path = require('path');
var imageStorage = multer.diskStorage({
// Destination to store image
// destination: 'assets/images/'+pathDir,
destination: (req, file, cb) => {
// console.log(req.get("path"));
// let pathdir = req.get("path");
cb(null, "assets/finance/")
// cb(null, "assets/words/" + pathdir + "/")
},
filename : (req, file, cb) => {
// let filename=file.originalname.split(".")[0];
let nik = req.nik;
let filedoc = 'fin_'+nik+'_' + Date.now() + path.extname(file.originalname);
// req.body.filedoc = filedoc;
// cb(null, filedoc);
req.body.filename = filedoc;
cb(null, filedoc);
// file.fieldname is name of the field (image)
// path.extname get the uploaded file extension
}
});
var imageUpload = multer({
storage: imageStorage,
limits: {
fileSize: '5mb' // 1000000 Bytes = 5 MB
},
fileFilter(req, file, cb) {
// if (!file.originalname.match(/\.(png|jpg|pdf)$/)) {
if (!file.originalname.match(/\.(docx|pdf)$/)) {
// upload only png and jpg format
req.fileValidationError = "Please upload a word document in ( docx / pdf ) max 5 mb";
cb(new Error('Please upload a word document in ( docx / pdf ) max 5 mb'), false);
}
else{
cb(null, true);
}
}
}).single("file-doc");
module.exports = (req, res, next) => {
try {
imageUpload(req,res, function(err){
try {
// if (err || err instanceof multer.MulterError){
if (err){
res.status(500).send({
"meta":{
"auth": false,
"code" : 500,
"message" : req.fileValidationError || err.toString(),
},
"data" :[]
});
} else {
next();
// console.log('The filename is ' + res.req.file.filename);
}
} catch (error) {
console.log("error "+error);
}
});
} catch (error) {
console.log("error " + error);
error.message = error.message;
error.statusCode = 500;
throw error;
}
}