<?php
// upload.php - 單檔案處理邏輯
function alert(string $msg): string {
return '';
}
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$uploadDir = __DIR__ . '/uploads/';
$maxSize = 2 * 1024 * 1024; // 2MB
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
exit(alert('請透過表單提交'));
}
$file = $_FILES['file'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
exit(alert('上傳錯誤:' . ($file['error'] ?? '未知')));
}
if ($file['size'] > $maxSize) {
exit(alert('檔案超過 ' . ($maxSize/1024/1024) . 'MB 限制'));
}
// 真實 MIME 驗證
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, $allowedTypes, true)) {
exit(alert('僅允許 JPG/PNG/GIF/WebP 圖片'));
}
// 確保目錄存在
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
exit(alert('無法建立上傳目錄'));
}
// 產生唯一檔名
$ext = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/webp'=>'webp'][$mime];
$filename = date('YmdHis') . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
$destPath = $uploadDir . $filename;
// 移動檔案
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
exit(alert('檔案儲存失敗'));
}
// 成功
echo alert('上傳成功:' . $filename);
?>
檔案上傳
圖片上傳
$_FILES 為空$_FILES['type']<?php
// upload.php 成功後改為顯示頁面而非 alert
if (move_uploaded_file($file['tmp_name'], $destPath)) {
$fileUrl = '/uploads/' . $filename;
?>
上傳成功
上傳成功!
檔名: = htmlspecialchars($filename) ?>
大小: = number_format($file['size']/1024, 1) ?> KB
類型: = htmlspecialchars($mime) ?>
| 現象 | 可能原因 | 解決 |
|---|---|---|
| $_FILES 為空 | 表單缺 enctype、檔案超過 post_max_size | 檢查表單、調大 php.ini 設定 |
| move_uploaded_file 失敗 | 目錄權限、磁碟空間、open_basedir 限制 | chmod 755、檢查錯誤日誌 |
| 上傳後無法顯示 | Nginx/Apache 未設定靜態檔案服務、路徑錯誤 | 確認 web root、URL 重寫規則 |
| 中文檔名亂碼 | 檔案系統編碼、URL 編碼不一致 | 強制使用隨機檔名 |
ondrop 事件 + FormData AJAXupload.onprogresscanvas.toBlob() 壓縮後再上傳