Files
Word/upload.php
2025-11-18 14:30:07 +08:00

41 lines
1.2 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
// 处理图片上传返回可访问的URL
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/auth.php';
require_api_auth();
$baseDir = __DIR__ . DIRECTORY_SEPARATOR . 'data';
$uploadsDir = $baseDir . DIRECTORY_SEPARATOR . 'uploads';
if (!is_dir($uploadsDir)) { mkdir($uploadsDir, 0777, true); }
if (!isset($_FILES['image'])) {
http_response_code(400);
echo json_encode(['error' => 'no file']);
exit;
}
$file = $_FILES['image'];
if ($file['error'] !== UPLOAD_ERR_OK) {
http_response_code(400);
echo json_encode(['error' => 'upload error']);
exit;
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (!preg_match('/^image\//', $mime)) {
http_response_code(400);
echo json_encode(['error' => 'not image']);
exit;
}
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$name = 'img_' . uniqid() . ($ext ? ('.' . preg_replace('/[^a-zA-Z0-9]/', '', $ext)) : '');
$dest = $uploadsDir . DIRECTORY_SEPARATOR . $name;
move_uploaded_file($file['tmp_name'], $dest);
// 构造相对URL基于XAMPP的htdocs路径
$url = '/PHP/wd/data/uploads/' . $name;
echo json_encode(['url' => $url], JSON_UNESCAPED_UNICODE);