File size: 2,375 Bytes
dc45f00 a5065b3 dc45f00 215c48f dc45f00 215c48f dc45f00 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
<?php
// 设置上传目录
$imageDir = 'img/';
$videoDir = 'videos/';
// 检查并创建目录
if (!is_dir($imageDir)) {
mkdir($imageDir, 0777, true);
}
if (!is_dir($videoDir)) {
mkdir($videoDir, 0777, true);
}
// 获取协议
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
// 如果是在 HuggingFace 空间上运行,强制使用 HTTPS
if (strpos($_SERVER['HTTP_HOST'], '.hf.space') !== false) {
$protocol = 'https://';
}
// 获取客户端IP和端口
$host = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol . $host . dirname($_SERVER['SCRIPT_NAME']) . '/';
// 准备响应数组
$response = ["code" => 400, "msg" => "failed"];
// 检查是否有文件上传
if ($_FILES) {
// 获取文件信息
$file = $_FILES['file'];
$filename = basename($file['name']);
$fileTmpPath = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];
// 设置文件名及上传路径
if (strpos($fileType, 'image') !== false) {
// 处理图片上传
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$newFilename = 'Image_' . time() . sprintf('%03d', rand(0, 999)) . '.' . $ext;
$uploadFilePath = $imageDir . $newFilename;
$urlPath = $baseUrl . $imageDir . $newFilename;
} elseif (strpos($fileType, 'video') !== false) {
// 处理视频上传
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$newFilename = 'Video_' . time() . sprintf('%03d', rand(0, 999)) . '.' . $ext;
$uploadFilePath = $videoDir . $newFilename;
$urlPath = $baseUrl . $videoDir . $newFilename;
} else {
// 无效的文件类型
$response['msg'] = 'Invalid file type';
echo json_encode($response);
exit;
}
// 移动文件到指定目录
if (move_uploaded_file($fileTmpPath, $uploadFilePath)) {
$response['code'] = 200;
$response['msg'] = 'success';
if (strpos($fileType, 'image') !== false) {
$response['img'] = $urlPath;
} elseif (strpos($fileType, 'video') !== false) {
$response['videos'] = $urlPath;
}
} else {
$response['msg'] = 'File upload failed';
}
} else {
$response['msg'] = 'No file uploaded';
}
// 返回JSON响应并替换\/为/
echo str_replace('\/', '/', json_encode($response));
?>
|