[ 'title' => '图片', 'dir' => '/image/' ], 'video' => [ 'title' => '视频', 'dir' => '/video/' ], 'voice' => [ 'title' => '声音', 'dir' => '/voice/' ], 'file' => [ 'title' => '文件', 'dir' => '/file/' ], ]; /** * 文件允许大小 * @access proetcted * @var array */ protected $file_allow_size = [ 'image' => 5120000,//5M 'video' => 20480000,//20M 'voice' => 20480000,//20M 'file' => 20480000,//20M ]; /** * 文件允许格式 * @access protected * @var array */ protected $file_allow_ext = [ 'image' => [ 'gif', 'jpg', 'jpeg', 'png', 'bmp' ], 'video' => [ 'mp4', 'avi', 'ogg', 'flv', 'webm', 'ogv', 'mpg' ], 'voice' => [ 'mp3', 'ogg', 'wav', 'm4a' ], 'file' => [], ]; public function _initialize() { parent::_initialize(); if (!empty(config('FILE_UPLOADS_DIR'))) { $this->upload_dir = config('FILE_UPLOADS_DIR'); } $this->domain = !empty($this->request->domain()) ? $this->request->domain() : ''; } /** * @上传文件 * @param * @access * @return */ public function upFile() { $type = !empty($this->request->param('type')) ? $this->request->param('type') : ''; if (empty($type)) { return ['status' => 0, 'msg' => 'error[expect type]']; } if (!in_array($type, array_keys($this->file_type))) { return ['status' => 0, 'msg' => 'error[type not exist]']; } try { $file = $this->request->file($type); } catch (\Exception $e) { return ['status' => 0, 'msg' => 'error[file empty]']; } if (empty($file)) { return ['status' => 0, 'msg' => 'error[file empty]']; } $res = $this->_upFile($file, $type); if ($res['status'] != 1) { return $res; } return ['status' => 200, 'msg' => 'success', 'data' => $res['data']]; } /** * @上传操作 * @param object $file * @param string $type * @access protected * @return array */ protected function _upFile(File $file, $type) { //验证文件类型 if (!empty($this->file_allow_ext[$type]) && $file->checkExt($this->file_allow_ext[$type]) === false) { return [ 'status' => 0, 'msg' => '文件格式不允许', ]; } //验证大小 if (!empty($this->file_allow_size[$type]) && $file->checkSize($this->file_allow_size[$type]) === false) { return [ 'status' => 0, 'msg' => '文件大小不符', ]; } $info = $file->move('.'.$this->upload_dir.$this->file_type[$type]['dir']); if (empty($info)) { return [ 'status' => 0, 'msg' => $file->getError(), ]; } return [ 'status' => 1, 'msg' => 'success', 'data' => [ 'ext' => $info->getExtension(), 'name' => $info->getFilename(), 'path' => $this->domain.str_replace("\\", "/", $this->upload_dir.$this->file_type[$type]['dir'].$info->getSaveName()), ], ]; } }