fea/nhat-dat-11042026-merge #1

Closed
minhnhat wants to merge 27 commits from UKSOURCE/cms.hailearning.edu.vn:fea/nhat-dat-11042026-merge into fea/nhat-13042028-merge-kiet-thien
2 changed files with 16 additions and 4 deletions
Showing only changes of commit e83f1827b8 - Show all commits

View File

@@ -66,17 +66,21 @@ async function finalizeUploadedImage(file, req, resizePreset) {
} }
const { finalFileName, finalPath } = getFinalUploadTarget(file, req, true); const { finalFileName, finalPath } = getFinalUploadTarget(file, req, true);
const finalPathMatchesInput = path.resolve(file.path) === path.resolve(finalPath);
await sharp(file.path) const sourceBuffer = fs.readFileSync(file.path);
const optimizedBuffer = await sharp(sourceBuffer)
.resize(preset.width, preset.height, { .resize(preset.width, preset.height, {
fit: 'contain', fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 }, background: { r: 0, g: 0, b: 0, alpha: 0 },
withoutEnlargement: true, withoutEnlargement: true,
}) })
.webp({ quality: preset.quality }) .webp({ quality: preset.quality })
.toFile(finalPath); .toBuffer();
if (fs.existsSync(file.path)) { fs.writeFileSync(finalPath, optimizedBuffer);
if (!finalPathMatchesInput && fs.existsSync(file.path)) {
try { try {
fs.unlinkSync(file.path); fs.unlinkSync(file.path);
} catch (cleanupError) { } catch (cleanupError) {

View File

@@ -34,6 +34,14 @@ const storage = multer.diskStorage({
// Lấy tên file gốc (sanitize để tránh ký tự đặc biệt) // Lấy tên file gốc (sanitize để tránh ký tự đặc biệt)
const originalName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_'); const originalName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
const resizePreset = req.query.resizePreset || '';
if (resizePreset) {
const parsedOriginalName = path.parse(originalName);
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
req.uploadFinalFileName = originalName;
return cb(null, `${parsedOriginalName.name}.__upload__${uniqueSuffix}${parsedOriginalName.ext}`);
}
const fullPath = path.join(uploadPath, originalName); const fullPath = path.join(uploadPath, originalName);
// Kiểm tra nếu file đã tồn tại // Kiểm tra nếu file đã tồn tại
@@ -159,4 +167,4 @@ module.exports = {
upload, upload,
uploadVideo, uploadVideo,
convertToWebp convertToWebp
}; };