enctype="multipart/form-data"$_FILES 錯誤碼move_uploaded_file()<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2097152"> <!-- 2MB,僅客戶端提示 -->
<input type="file" name="avatar" accept="image/*" required>
<button type="submit">上傳</button>
</form>
<?php
declare(strict_types=1);
const UPLOAD_DIR = __DIR__ . '/uploads/';
const ALLOWED_MIME = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const MAX_SIZE = 2 * 1024 * 1024; // 2MB
// 確保目錄存在
if (!is_dir(UPLOAD_DIR)) {
mkdir(UPLOAD_DIR, 0755, true);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit('Method Not Allowed');
}
$file = $_FILES['avatar'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
$errors = [
UPLOAD_ERR_INI_SIZE => '超過 php.ini upload_max_filesize',
UPLOAD_ERR_FORM_SIZE => '超過表單 MAX_FILE_SIZE',
UPLOAD_ERR_PARTIAL => '上傳不完整',
UPLOAD_ERR_NO_FILE => '未選擇檔案',
];
exit('上傳錯誤:' . ($errors[$file['error']] ?? '未知錯誤'));
}
// 驗證檔案大小
if ($file['size'] > MAX_SIZE) {
exit('檔案過大,限制 2MB');
}
// 驗證 MIME(需 finfo 擴展)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, ALLOWED_MIME, true)) {
exit('不允許的檔案類型');
}
// 產生安全檔名
$ext = match ($mime) {
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
default => 'bin',
};
$filename = bin2hex(random_bytes(16)) . '.' . $ext;
$dest = UPLOAD_DIR . $filename;
// 移動檔案
if (!move_uploaded_file($file['tmp_name'], $dest)) {
exit('檔案儲存失敗');
}
// 成功回應
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'filename' => $filename,
'url' => '/uploads/' . $filename,
'size' => $file['size'],
], JSON_UNESCAPED_UNICODE);
<input type="file" id="avatar" accept="image/*">
<img id="preview" style="max-width:200px;display:none">
<script>
document.getElementById('avatar').addEventListener('change', e => {
const file = e.target.files[0];
if (file) {
document.getElementById('preview').src = URL.createObjectURL(file);
document.getElementById('preview').style.display = 'block';
}
});
// AJAX 上傳
async function upload() {
const formData = new FormData();
formData.append('avatar', document.getElementById('avatar').files[0]);
const res = await fetch('upload.php', {method: 'POST', body: formData});
const data = await res.json();
console.log(data);
}
</script>
use Psr\Http\Message\UploadedFileInterface;
function handleUpload(UploadedFileInterface $file): string {
$file->moveTo(UPLOAD_DIR . $filename);
return $filename;
}
原始來源:www.111cn.net