<?php namespace app\controller\api\file; use app\controller\api\Base; use app\model\File; use app\model\System; use app\service\Image; use app\validate\Upload as VUpload; use think\facade\Config; use think\facade\Filesystem; use think\facade\Lang; use think\response\Json; /** * 文件上传 * * Class Upload * @package app\controller\api\file */ class Upload extends Base { protected $noNeedLogin = []; // 图片上传是否进行压缩[max-width:1920px] private bool $isCompress = true; private $validate = null; // 文件上传对外默认保存目录(相对路径) private string $uploadPath = ''; // 文件上传对外默认保存目录是否有写权限 private bool $uploadPathIsWritable = false; protected bool $saveToOos = false; public function initialize() { parent::initialize(); $system = System::getSystem(); if (!empty($system)) { $this->isCompress = $system['compress'] ?? true; } $this->validate = new VUpload(); $this->uploadPath = Config::get('filesystem.disks.local.url'); $savePath = app()->getRootPath() . 'public' . $this->uploadPath; if (!is_dir($savePath)) { @mkdir($savePath, 0777); } if(is_writable($savePath)){ $this->uploadPathIsWritable = true; } $this->cancelTimeLimit(); } /** * 通用文件上传 * @return Json */ public function file() { $file = request()->file('file'); if (empty($file)) { return $this->json(4001, '请上传的文件'); } if($this->validate->checkFile($file)){ try{ if(!$this->uploadPathIsWritable){ throw new \Exception('上传文件夹需要写入权限'); } $src = Filesystem::putFile(date('Ymd'), $file, 'uniqid'); $src = $this->uploadPath . '/' . $src; $return['src'] = $src; $return['name'] = $file->getOriginalName(); } catch (\Exception $e) { return $this->json(4003, $e->getMessage()); } return $this->json(0,'success', $return); }else{ $errorMsg = Lang::get($this->validate->getError()); return $this->json(4002, $errorMsg); } } /** * 通用图片上传 * @return Json */ public function image() { $image = request()->file('image'); if (empty($image)) { return $this->json(4001, '请上传图片文件'); } if($this->validate->checkImage($image)){ try{ if(!$this->uploadPathIsWritable){ throw new \Exception('上传文件夹需要写入权限'); } $src = Filesystem::putFile(date('Ymd'), $image, 'uniqid'); $src = $this->uploadPath . '/' . $src; $return['src'] = $src; if($this->isCompress){ Image::resize($src); } } catch (\Exception $e) { return $this->json(4003, $e->getMessage()); } return $this->json(0, 'success', $return); }else{ $errorMsg = Lang::get($this->validate->getError()); return $this->json(4002, $errorMsg); } } }