From e83f1827b89f4bf0b6a8a07ee8f077bbdd8f869c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=E1=BB=91ng=20Th=C3=A0nh=20=C4=90=E1=BA=A1t?= <84076965+tongthanhdat009@users.noreply.github.com> Date: Sat, 11 Apr 2026 11:09:16 +0700 Subject: [PATCH] fix: fix resized image uploads --- controllers/uploadController.js | 10 +++++++--- middleware/upload.js | 10 +++++++++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/controllers/uploadController.js b/controllers/uploadController.js index 7d4f80c..ff8042f 100644 --- a/controllers/uploadController.js +++ b/controllers/uploadController.js @@ -66,17 +66,21 @@ async function finalizeUploadedImage(file, req, resizePreset) { } 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, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 }, withoutEnlargement: true, }) .webp({ quality: preset.quality }) - .toFile(finalPath); + .toBuffer(); - if (fs.existsSync(file.path)) { + fs.writeFileSync(finalPath, optimizedBuffer); + + if (!finalPathMatchesInput && fs.existsSync(file.path)) { try { fs.unlinkSync(file.path); } catch (cleanupError) { diff --git a/middleware/upload.js b/middleware/upload.js index 7808000..f9942a7 100644 --- a/middleware/upload.js +++ b/middleware/upload.js @@ -34,6 +34,14 @@ const storage = multer.diskStorage({ // 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 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); // Kiểm tra nếu file đã tồn tại @@ -159,4 +167,4 @@ module.exports = { upload, uploadVideo, convertToWebp -}; \ No newline at end of file +};