47 lines
1.1 KiB
JavaScript
47 lines
1.1 KiB
JavaScript
|
|
import multer from "multer";
|
||
|
|
import path from "path";
|
||
|
|
import response from "../../response.js";
|
||
|
|
|
||
|
|
const memoryStorage = multer.memoryStorage();
|
||
|
|
|
||
|
|
const fileFilter = (req, file, cb) => {
|
||
|
|
const ext = path.extname(file.originalname).toLowerCase();
|
||
|
|
if (ext === ".csv" || ext === ".xlsx") {
|
||
|
|
cb(null, true);
|
||
|
|
} else {
|
||
|
|
cb(
|
||
|
|
new Error("Invalid file type, only .csv and .xlsx files are allowed!"),
|
||
|
|
false
|
||
|
|
);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
const upload = multer({
|
||
|
|
storage: memoryStorage,
|
||
|
|
fileFilter,
|
||
|
|
limits: { fileSize: 2 * 1024 * 1024 },
|
||
|
|
}).fields([{ name: "file", maxCount: 1 }]);
|
||
|
|
|
||
|
|
const handleCsvUpload = (req, res, next) => {
|
||
|
|
upload(req, res, (err) => {
|
||
|
|
if (err) {
|
||
|
|
return response(400, null, err.message, res);
|
||
|
|
}
|
||
|
|
|
||
|
|
const files = req.files;
|
||
|
|
const file = files?.file ? files.file[0] : null;
|
||
|
|
|
||
|
|
if (!file) {
|
||
|
|
return response(400, null, "No file uploaded!", res);
|
||
|
|
}
|
||
|
|
|
||
|
|
req.uploadedFile = {
|
||
|
|
buffer: file.buffer,
|
||
|
|
extension: path.extname(file.originalname).toLowerCase(),
|
||
|
|
};
|
||
|
|
next();
|
||
|
|
});
|
||
|
|
};
|
||
|
|
|
||
|
|
export default handleCsvUpload;
|