I am creating an employee payroll application where i want to upload and download xlsx file in records section. Controller works fine. Postman gives response as file uploaded successfully but the file is not uploaded in public/docs directory. Am i doing something wrong while serving static directory.
Static directory serving code.
app.use(express.static(path.join(process.cwd(), 'public')));
Router to uploading file
router.post('/', protect, upload.single("file"), fileUpload)
router.get('/download', fileDownload)
Controller for uploading file
const storage = multer.diskStorage({
destination: (req, file, cb) => {
if(!fs.existsSync(directory)){
fs.mkdirSync(directory)
console.log("Running 123", directory);
cb(null, directory)
}else{
console.log("Directory already exists", directory);
cb(null, directory)
}
},
filename: (req, file, cb) => {
cb(null, Date.now() + "-" + file.originalname)
}
})
const upload = multer({storage, fileFilter: (req, file, callback) => {
if(['xls', 'xlsx', 'NUMBERS'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1){
return callback(new Error('Wrong extension type'));
}
callback(null, true);
}})
const fileUpload = function(req, res) {
let recordPath = path.join(process.cwd(),'public/docs/' + req.file.filename)
importToDb(recordPath);
fs.unlinkSync(recordPath);
res.json({'msg': 'Employee record uploaded and successfully imported', 'file': req.file});
};
const fileDownload = function(req, res) {
let template = path.join(process.cwd(), '/public/docs/Employee_Record_Template.xlsx');
res.download(template);
};
Directory Structure is
payroll
-bin
-public
-docs
-emailTemplates
-images
-javascripts
-stylesheets
-fonts
-src
-config
-controllers
-api
-middlewares
-models
-routes
app.js