Files
011-ai-interview/docs/upload.php
2026-01-23 13:57:48 +08:00

94 lines
2.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 简历文件上传接口
*
* 放置位置: /www/wwwroot/files.test.ai.ireborn.com.cn/upload.php
*
* 请求方式: POST
* 参数:
* - file: 文件multipart/form-data
* - token: 验证令牌(防止滥用)
*
* 返回:
* - {"code": 0, "url": "http://files.test.ai.ireborn.com.cn/resumes/xxx.pdf"}
* - {"code": 1, "error": "错误信息"}
*/
// 配置
$UPLOAD_DIR = '/www/wwwroot/files.test.ai.ireborn.com.cn/resumes/';
$BASE_URL = 'http://files.test.ai.ireborn.com.cn/resumes/';
$SECRET_TOKEN = 'your_secret_token_here_change_me'; // 请修改为你自己的密钥
$MAX_SIZE = 20 * 1024 * 1024; // 20MB
$ALLOWED_TYPES = ['application/pdf'];
// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
// 处理 OPTIONS 预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
// 只允许 POST 请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['code' => 1, 'error' => 'Method not allowed']);
exit;
}
// 验证令牌
$token = $_POST['token'] ?? $_SERVER['HTTP_X_UPLOAD_TOKEN'] ?? '';
if ($token !== $SECRET_TOKEN) {
http_response_code(403);
echo json_encode(['code' => 1, 'error' => 'Invalid token']);
exit;
}
// 检查文件是否上传
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
$error_msg = isset($_FILES['file']) ? 'Upload error: ' . $_FILES['file']['error'] : 'No file uploaded';
echo json_encode(['code' => 1, 'error' => $error_msg]);
exit;
}
$file = $_FILES['file'];
// 检查文件大小
if ($file['size'] > $MAX_SIZE) {
echo json_encode(['code' => 1, 'error' => 'File too large (max 20MB)']);
exit;
}
// 检查文件类型(通过扩展名)
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($ext !== 'pdf') {
echo json_encode(['code' => 1, 'error' => 'Invalid file type. Only PDF allowed.']);
exit;
}
// 生成文件名
$file_id = 'resume_' . bin2hex(random_bytes(6));
$filename = $file_id . '.pdf';
$filepath = $UPLOAD_DIR . $filename;
// 确保目录存在
if (!is_dir($UPLOAD_DIR)) {
mkdir($UPLOAD_DIR, 0755, true);
}
// 移动文件
if (move_uploaded_file($file['tmp_name'], $filepath)) {
$url = $BASE_URL . $filename;
echo json_encode([
'code' => 0,
'url' => $url,
'file_id' => $file_id,
'filename' => $filename
]);
} else {
echo json_encode(['code' => 1, 'error' => 'Failed to save file']);
}