Blame view

稻城亚丁小程序/backend/app/controller/api/Upload.php 1.39 KB
bc518174   王天杨   提交两个项目文件
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
  <?php
  declare(strict_types=1);
  
  namespace app\controller\api;
  
  use app\BaseController;
  use app\service\AuthContext;
  
  class Upload extends BaseController
  {
      public function image()
      {
          if (!AuthContext::mpUser()) {
              return json(['code' => 401, 'msg' => '未授权', 'data' => []]);
          }
  
          $file = $this->request->file('file');
          if (!$file) {
              return json(['code' => 400, 'msg' => '请选择文件', 'data' => []]);
          }
  
          $max = 10 * 1024 * 1024;
          if ($file->getSize() > $max) {
              return json(['code' => 400, 'msg' => '文件不能超过 10MB', 'data' => []]);
          }
          $ext = strtolower((string) $file->extension());
          if (!in_array($ext, ['jpg', 'jpeg', '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]]);
      }
  }