圖片上傳是 Web 開發基礎功能,涉及前端表單構造、後端文件驗證、重命名、存儲、安全防護等多個環節。本文提供一套完整的前後端代碼,涵蓋格式驗證、隨機命名、目錄自動創建、錯誤處理等實用技巧。
<form name="form1" method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="pic" accept="image/*" required>
<input type="submit" name="submit" value="開始上傳" class="button">
</form>
關鍵點:enctype="multipart/form-data"、accept="image/*" 限制文件選擇框過濾。
php.ini 的 upload_max_filesize、post_max_size。md5(時間.隨機數) + 原擴展名,防止覆蓋與腳本注入。move_uploaded_file() 確保文件來自合法上傳。<?php
header('Content-Type: application/json; charset=utf-8');
$config = [
'rootPath' => __DIR__ . '/uploads/',
'maxSize' => 5 * 1024 * 1024, // 5MB
'allowTypes' => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
'allowExts' => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
];
$resp = ['code'=>0, 'msg'=>'', 'data'=>null];
if (!isset($_FILES['pic']) || $_FILES['pic']['error'] !== UPLOAD_ERR_OK) {
$resp['msg'] = '上傳失敗:' . ($_FILES['pic']['error'] ?? '未知錯誤');
echo json_encode($resp);
exit;
}
$file = $_FILES['pic'];
// 1. 大小檢查
if ($file['size'] > $config['maxSize']) {
$resp['msg'] = '文件過大,限制 ' . ($config['maxSize']/1024/1024) . 'MB';
echo json_encode($resp);
exit;
}
// 2. MIME 類型檢查
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (!in_array($mime, $config['allowTypes'])) {
$resp['msg'] = '禁止的文件類型:' . $mime;
echo json_encode($resp);
exit;
}
// 3. 擴展名檢查
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $config['allowExts'])) {
$resp['msg'] = '禁止的擴展名:' . $ext;
echo json_encode($resp);
exit;
}
// 4. 目標目錄(按日期)
$dateDir = date('Y/m/d/');
$destDir = $config['rootPath'] . $dateDir;
if (!is_dir($destDir)) {
mkdir($destDir, 0755, true);
}
// 5. 隨機文件名
$newName = md5(microtime(true) . mt_rand(1000,9999)) . '.' . $ext;
$destPath = $destDir . $newName;
// 6. 移動文件
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
$resp['msg'] = '文件保存失敗,請檢查目錄權限';
echo json_encode($resp);
exit;
}
// 7. 成功返回
$resp['code'] = 1;
$resp['msg'] = '上傳成功';
$resp['data'] = [
'path' => $dateDir . $newName,
'fullPath' => $destPath,
'size' => $file['size'],
'mime' => $mime,
];
echo json_encode($resp);
getimagesize() 或 imagecreatefromstring() 驗證是否真實圖片。// 使用 FormData + fetch
const formData = new FormData();
formData.append('pic', fileInput.files[0]);
fetch('upload.php', {method:'POST', body:formData})
.then(r => r.json())
.then(res => { if(res.code) console.log('成功', res.data); else alert(res.msg); });
這套方案從前端到後端覆蓋了圖片上傳的完整鏈路,代碼結構清晰,安全措施完善,可直接投入生產環境或作為基礎組件進一步擴展。