param('size', ConfServiceFacade::get('system.upload.size')); if (!$this->checkSize($fileSize, $allowSize)) { return false; } $allowExt = request()->param('mime', ConfServiceFacade::get('system.upload.mime')); if (!$this->checkExt($fileName, $fileExt, $allowExt)) { return false; } if (!$this->checkMime($fileMime)) { return false; } return true; } /** * 检测上传文件大小 * @param $fileSize * @param string $allowSize * @return bool */ public function checkSize($fileSize, $allowSize = '') { $allowSize = str_replace(' ', '', $allowSize); $allowUploadSizeConf = ConfServiceFacade::get('system.upload.size'); // 没有配置,也没有传入上传文件大小限制参数,即程序上不限制上传文件大小 if (!$allowUploadSizeConf && !$allowSize) { return true; } $maxSize = $allowSize ? $allowSize : $allowUploadSizeConf; preg_match('/(\d+)(\w+)/', $maxSize, $matches); $type = strtolower($matches[2]); $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3]; $maxSize = (int)$maxSize * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0); if ($fileSize > $maxSize) { $this->setError('上传失败,文件大小超过 ' . $allowSize); return false; } return true; } /** * 检测上传文件后缀 * @param $fileName * @param $fileExt * @param string $allowExt * @return bool */ public function checkExt($fileName, $fileExt, $allowExt = '') { $allowExtArr = explode(',', strtolower($allowExt)); //禁止上传PHP和HTML文件 if (in_array($fileExt, ['php', 'html', 'htm'])) { $this->setError('上传失败,禁止上传php和html文件'); return false; } //验证文件后缀 $allowExtConf = ConfServiceFacade::get('system.upload.mime'); // 没有配置,也没有传入上传文件大小限制参数,即程序上不限制上传文件大小 if (!$allowExtConf && !$allowExt) { $this->setError('上传失败,允许上传的文件后缀为空,请到系统配置 - 上传配置进行设置'); return false; } if ($allowExt !== '*' && (!in_array($fileExt, $allowExtArr))) { $this->setError('上传失败,允许上传的文件后缀为' . $allowExt . ',实际上传文件[ ' . $fileName . ' ]的后缀为' . $fileExt); return false; } return true; } /** * 检测上传文件类型 * @param $fileMime * @return bool */ public function checkMime($fileMime) { //禁止上传PHP和HTML文件 if (in_array($fileMime, ['text/x-php', 'text/html'])) { $this->setError('上传失败,禁止上传php和html文件'); return false; } return true; } /** * 编辑器内容,添加上传文件的域名前缀,一般提供给数据模型层getFiledAttr方法调用 * @param $string * @param $uploadType * @return string|string[]|null */ static public function addUploadDomain($string, $uploadType = 'local') { $defaultType = ConfServiceFacade::get('system.upload.defaultType', 'local'); if($uploadType == 'default') $uploadType = $defaultType; $uploadDomain = self::getUploadDomain($uploadType, 'via'); //ueditor编辑器正则替换所有的图片、视频、音频 /* $string = preg_replace("/(+)/is", "\${1}{$uploadDomain}\${2}\${3}", $string);*/ preg_match_all("/(+)/is", $string, $matches); if ($matches && isset($matches['2'])) { foreach ($matches['2'] as $item) { if (substr($item, 0, 4) != 'http') { $string = str_replace($item, $uploadDomain . $item, $string); } } } $string = preg_replace("/(