初始化版本
This commit is contained in:
40
upload.php
Normal file
40
upload.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?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);
|
||||
Reference in New Issue
Block a user