$maxSize) { jsonResponse(false, 'ขนาดไฟล์ต้องไม่เกิน 5MB'); } // สร้างโฟลเดอร์สำหรับเก็บไฟล์ถ้ายังไม่มี $uploadDir = '../uploads/driver_docs/'; if (!is_dir($uploadDir)) { mkdir($uploadDir, 0755, true); } // สร้างชื่อไฟล์ใหม่เพื่อป้องกันชื่อซ้ำ และปัญหาภาษาไทย $extension = pathinfo($file['name'], PATHINFO_EXTENSION); $newFileName = 'drv_' . $driver_id . '_' . time() . '_' . uniqid() . '.' . $extension; $destination = $uploadDir . $newFileName; $dbPath = 'uploads/driver_docs/' . $newFileName; // ย้ายไฟล์ไปยังโฟลเดอร์ปลายทาง if (move_uploaded_file($file['tmp_name'], $destination)) { try { // บันทึกข้อมูลลงฐานข้อมูล $stmt = $pdo->prepare("INSERT INTO driver_documents (driver_id, original_name, file_name, file_path) VALUES (?, ?, ?, ?)"); $stmt->execute([ $driver_id, $file['name'], $newFileName, $dbPath ]); jsonResponse(true, 'อัปโหลดไฟล์สำเร็จ'); } catch (PDOException $e) { // หากบันทึกฐานข้อมูลลบเหลว ให้ลบไฟล์ที่อัปโหลดไปแล้วด้วย if (file_exists($destination)) { unlink($destination); } jsonResponse(false, 'Database Error: ' . $e->getMessage()); } } else { jsonResponse(false, 'ไม่สามารถบันทึกไฟล์ได้ กรุณาลองใหม่อีกครั้ง'); } ?>