Upload.php
2.17 KB
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
<?php
declare(strict_types=1);
namespace app\controller\admin;
use app\BaseController;
use Throwable;
/**
* 管理后台:图片上传(与小程序 upload 存盘规则一致)
*/
class Upload extends BaseController
{
public function image()
{
try {
$file = $this->request->file('file');
if (!$file) {
return json(['code' => 400, 'msg' => '请选择文件(表单字段名须为 file)', 'data' => []]);
}
$max = 10 * 1024 * 1024;
if ($file->getSize() > $max) {
return json(['code' => 400, 'msg' => '文件不能超过 10MB', 'data' => []]);
}
$ext = strtolower((string) $file->extension());
if ($ext === 'jpeg') {
$ext = 'jpg';
}
if ($ext === '' || !in_array($ext, ['jpg', 'png', 'webp', 'gif'], true)) {
$mime = strtolower((string) $file->getOriginalMime());
$ext = match (true) {
str_contains($mime, 'jpeg') => 'jpg',
str_contains($mime, 'png') => 'png',
str_contains($mime, 'webp') => 'webp',
str_contains($mime, 'gif') => 'gif',
default => '',
};
}
if ($ext === '' || !in_array($ext, ['jpg', 'png', 'webp', 'gif'], true)) {
return json(['code' => 400, 'msg' => '仅支持 jpg/png/webp/gif', 'data' => []]);
}
$subdir = date('Ymd');
$root = public_path() . 'uploads' . DIRECTORY_SEPARATOR . $subdir;
if (!is_dir($root) && !mkdir($root, 0755, true) && !is_dir($root)) {
return json(['code' => 500, 'msg' => '无法创建上传目录', 'data' => []]);
}
$saveName = bin2hex(random_bytes(8)) . '.' . $ext;
$file->move($root, $saveName);
$url = '/uploads/' . $subdir . '/' . $saveName;
return json(['code' => 0, 'msg' => 'ok', 'data' => ['url' => $url]]);
} catch (Throwable $e) {
return json(['code' => 500, 'msg' => '上传失败:' . $e->getMessage(), 'data' => []]);
}
}
}