Я хочу запустить пользовательскую проверку на .xlsx
перед загрузкой.Я уже написал базовую проверку, но моя загрузка не работает.
const express = require('express');
const app = express();
const multer = require('multer');
const router = express.Router();
const uploadExcel = require('./excelMiddleware');
const multerS = multer();
const upload = multer({
dest:'excel',
fileFilter(res, file, cb){
if(!file.originalname.match(/\.(xls|xlsx)$/)){
return cb(new Error('Please upload a excel file'));
}
cb(undefined, true)
}
}).single('file');
router.post('/upload', multerS.single('file'), uploadExcel, upload, (req, res) => {
upload(req, res, function (err, data) {
if (err) throw err;
})
res.send('<h1>file uploaded</h1>')
})
router.get('*', (req, res) => {
res.send('<h1>Page not found</h1>')
})
app.use(router);
app.listen(8000, ()=> {
console.log('Server stared')
})
excelMiddleware.js
const XLSX = require('xlsx');
const { CONTACT } = require('./column.config');
const _ = require('lodash');
const uploadExcel = (req, res, next) => {
try{
const columnMapper = CONTACT;
const workbook = XLSX.read(req.file.buffer, {type:'buffer'});
const sheetName = workbook.SheetNames;
const excelJson = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName[0]]);
if(!excelJson.length) {
throw Error("Blank sheet");
}
const columnCheck = Object.keys(excelJson[0]);
const isColumnEqual = _.isEqual(columnMapper, columnCheck);
if(!isColumnEqual){
throw Error("Blank sheet");
}
next();
}
catch(e){
console.log(e)
return res.status(400).send({error:e.message});
}
}
module.exports = uploadExcel;