Files
gravity/เว็บไซต์หน่วยงานภายใน/api/upload_file.php
T
2026-09-16 23:20:08 +07:00

130 lines
4.8 KiB
PHP

<?php
// api/upload_file.php - Upload file to Google Drive via Apps Script Web App
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
// Set higher limits for large file uploads to GAS (70MB+ requires a lot of memory for base64 & JSON)
set_time_limit(600);
ini_set('memory_limit', '1024M');
ini_set('post_max_size', '128M');
ini_set('upload_max_filesize', '128M');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
echo json_encode(['status' => 'error', 'message' => 'No file uploaded or upload error']);
exit;
}
$folderId = $_POST['folderId'] ?? '';
if (empty($folderId)) {
echo json_encode(['status' => 'error', 'message' => 'Missing Google Drive Folder ID. ผู้ดูแลระบบยังไม่ได้ตั้งค่า Folder ID ให้กับหน่วยงานนี้']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
// Get GAS URL from system settings
$settingsStmt = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'gdrive_gas_url'");
$gasUrlRow = $settingsStmt->fetch();
$gasUrl = $gasUrlRow ? $gasUrlRow['setting_value'] : '';
if (empty($gasUrl)) {
echo json_encode(['status' => 'error', 'message' => 'Super Admin ยังไม่ได้ตั้งค่า Google Apps Script Web App URL']);
exit;
}
$fileTmpPath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileMimeType = mime_content_type($fileTmpPath);
if (!$fileMimeType) {
$fileMimeType = $_FILES['file']['type'];
}
$fileData = file_get_contents($fileTmpPath);
$base64 = base64_encode($fileData);
$payload = json_encode([
'filename' => $fileName,
'mimeType' => $fileMimeType,
'base64' => $base64,
'folderId' => $folderId
]);
// Send to GAS via cURL
$ch = curl_init($gasUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Handle redirect manually to prevent POST/GET confusion
curl_setopt($ch, CURLOPT_HEADER, true); // Include headers to parse Location
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
if(curl_errno($ch)) {
throw new \Exception(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headerStr = substr($response, 0, $headerSize);
$bodyStr = substr($response, $headerSize);
curl_close($ch);
// If GAS rejects because payload is too large
if ($httpCode === 413) {
echo json_encode(['status' => 'error', 'message' => 'ขนาดไฟล์ใหญ่เกินกว่าที่ Google Drive จะรับได้ (จำกัดการส่งข้อมูลที่ 50MB)']);
exit;
}
// If GAS returns a redirect (e.g. 302, 307)
if ($httpCode >= 300 && $httpCode < 400) {
if (preg_match('/^Location:\s*([^\r\n]+)/im', $headerStr, $matches)) {
$redirectUrl = trim($matches[1]);
// Force a GET request to the redirect URL
$ch2 = curl_init($redirectUrl);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch2, CURLOPT_HTTPGET, true); // Force GET
curl_setopt($ch2, CURLOPT_TIMEOUT, 60);
$bodyStr = curl_exec($ch2);
if(curl_errno($ch2)) {
throw new \Exception(curl_error($ch2));
}
curl_close($ch2);
} else {
throw new \Exception("GAS returned redirect but no Location header found.");
}
}
$resData = json_decode($bodyStr, true);
if ($resData && isset($resData['status']) && $resData['status'] === 'success') {
echo json_encode([
'status' => 'success',
'message' => 'File uploaded to Google Drive',
'fileId' => $resData['fileId'] ?? null,
'url' => $resData['url'] ?? null,
'fileName' => $fileName,
'fileSize' => $_FILES['file']['size']
]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Google Apps Script Error: ' . ($resData['message'] ?? $response)]);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Upload Error: ' . $e->getMessage()]);
}
?>