backend_adaptive_learning/middlewares/upload.js
2024-08-12 09:44:06 +07:00

75 lines
2.0 KiB
JavaScript

import multer from "multer";
import crypto from "crypto";
import path from "path";
import fs from "fs";
import response from "../response.js";
const memoryStorage = multer.memoryStorage();
const fileFilter = (req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
if (ext === ".png" || ext === ".jpg" || ext === ".jpeg") {
cb(null, true);
} else {
cb(
new Error(
"Invalid file type, only .png, .jpg, and .jpeg files are allowed!"
),
false
);
}
};
const upload = multer({
storage: memoryStorage,
fileFilter,
limits: { fileSize: 5 * 1024 * 1024 }, // Limit file size to 5MB
}).fields([
{ name: "icon", maxCount: 1 },
{ name: "thumbnail", maxCount: 1 },
]);
const saveFileToDisk = (file) => {
const md5sum = crypto
.createHash("md5")
.update(Date.now().toString())
.digest("hex");
const ext = path.extname(file.originalname);
const filename = `${md5sum}${ext}`;
const filepath = path.join("public/uploads", filename);
fs.writeFileSync(filepath, file.buffer);
return filename;
};
const handleUpload = (req, res, next) => {
upload(req, res, (err) => {
if (err) {
return response(400, null, err.message, res);
}
const files = req.files;
const icon = files?.icon ? files.icon[0] : null;
const thumbnail = files?.thumbnail ? files.thumbnail[0] : null;
try {
// Validate icon and thumbnail before saving
if (icon && thumbnail) {
const iconFilename = saveFileToDisk(icon);
const thumbnailFilename = saveFileToDisk(thumbnail);
// Update the filenames in the request object for further processing
req.body.icon = iconFilename;
req.body.thumbnail = thumbnailFilename;
next();
} else {
return response(400, null, "Both icon and thumbnail are required", res);
}
} catch (error) {
return response(500, null, "Internal Server Error", res);
}
});
};
export default handleUpload;