57 lines
1.7 KiB
PHP
57 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
class UploadController
|
|
{
|
|
public static function upload(): void
|
|
{
|
|
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => '请选择要上传的文件']);
|
|
return;
|
|
}
|
|
|
|
$file = $_FILES['file'];
|
|
$allowedTypes = [
|
|
'jpg', 'jpeg', 'png', 'gif', 'webp',
|
|
'js', 'ts', 'py', 'java', 'cpp', 'c', 'html', 'css', 'json', 'xml',
|
|
'txt', 'md', 'go', 'rs', 'php', 'rb', 'sql', 'yaml', 'yml', 'sh', 'bat'
|
|
];
|
|
|
|
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
|
|
|
|
if (!in_array($ext, $allowedTypes)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => '不支持的文件类型: .' . $ext]);
|
|
return;
|
|
}
|
|
|
|
if ($file['size'] > 10 * 1024 * 1024) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => '文件大小不能超过10MB']);
|
|
return;
|
|
}
|
|
|
|
$filename = uniqid() . '.' . $ext;
|
|
$uploadDir = __DIR__ . '/../../public/uploads/';
|
|
$filepath = $uploadDir . $filename;
|
|
|
|
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => '文件上传失败']);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => [
|
|
'url' => '/uploads/' . $filename,
|
|
'name' => $file['name'],
|
|
'size' => $file['size'],
|
|
'type' => $ext
|
|
]
|
|
]);
|
|
}
|
|
}
|