uploads และ downloads
This commit is contained in:
@@ -2,6 +2,7 @@ import multer from 'multer'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { sendError } from '../utils/response.js'
|
||||
import { getDTM } from '../utils/date.js'
|
||||
|
||||
const tempDir = 'uploads/temp'
|
||||
if (!fs.existsSync(tempDir)) {
|
||||
@@ -13,8 +14,21 @@ const storage = multer.diskStorage({
|
||||
cb(null, tempDir)
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
|
||||
cb(null, uniqueSuffix + path.extname(file.originalname))
|
||||
// ดึงนามสกุลไฟล์
|
||||
const ext = path.extname(file.originalname);
|
||||
|
||||
// ดึงชื่อไฟล์เดิม (ตัดนามสกุลออก)
|
||||
const originalName = path.basename(file.originalname, ext);
|
||||
|
||||
// Clean ชื่อไฟล์: เปลี่ยน space เป็น _, ลบอักขระพิเศษ, เหลือแค่ภาษาอังกฤษ ตัวเลข และ - _
|
||||
const cleanName = originalName.replace(/[^a-zA-Z0-9]/g, '_').substring(0, 100);
|
||||
|
||||
// Format: YYYYMMDDHHmm-Random-CleanName.ext
|
||||
// ตัวอย่าง: 202511300930-1234-System_Req.docx
|
||||
const dtm = getDTM();
|
||||
const random = Math.round(Math.random() * 1E4);
|
||||
|
||||
cb(null, `${dtm}-${random}-${cleanName}${ext}`);
|
||||
}
|
||||
})
|
||||
|
||||
@@ -59,20 +73,16 @@ function verifyFileSignature(filePath) {
|
||||
}
|
||||
|
||||
export const uploadMiddleware = (req, res, next) => {
|
||||
// เปลี่ยนเป็น .array() เพื่อรับหลายไฟล์ (รองรับสูงสุด 10 ไฟล์ต่อครั้ง)
|
||||
const uploadHandler = upload.array('prjdoc', 10)
|
||||
|
||||
uploadHandler(req, res, (err) => {
|
||||
if (err) return res.status(400).json(sendError(err.message))
|
||||
|
||||
// ถ้าไม่มีไฟล์ ข้ามไป
|
||||
if (!req.files || req.files.length === 0) return next()
|
||||
|
||||
// Loop ตรวจสอบ Signature ทุกไฟล์
|
||||
for (const file of req.files) {
|
||||
const isSafe = verifyFileSignature(file.path)
|
||||
if (!isSafe) {
|
||||
// ลบไฟล์ทั้งหมดทิ้งทันทีถ้าเจอไฟล์อันตรายแม้แต่ไฟล์เดียว
|
||||
req.files.forEach(f => {
|
||||
if (fs.existsSync(f.path)) fs.unlinkSync(f.path)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user