isInternal ? $this->uploadByInternal() : $this->uploadByExternal(); } /** * 外部上传(指用户上传,需验证文件类型、大小) */ private function uploadByExternal() { $saveName = ''; // 验证文件并上传 try{ $saveName = Filesystem::disk('public')->putFile( '', $this->file); }catch (\Exception $e){ log_write('文件上传异常:'.$e->getMessage()); } return $saveName; } /** * 内部上传(指系统上传,信任模式) */ private function uploadByInternal() { // 上传目录 $uplodDir = public_path() . '/uploads'; // 要上传图片的本地路径 $realPath = $this->getRealPath(); if (!rename($realPath, "{$uplodDir}/$this->fileName")) { $this->error = 'upload write error'; return false; } return true; } /** * 删除文件 */ public function delete($fileName) { // 文件所在目录 $filePath = public_path() . "/uploads/{$fileName}"; return !file_exists($filePath) ?: unlink($filePath); } /** * 返回文件路径 */ public function getFileName() { return $this->fileName; } /** * 生成缩略图(将原图复制到新路径,然后将原路径变为缩略图) by lyzflash */ public function createThumb($saveName, $is_original = false) { // 获取上传设置 $config = SettingModel::getItem('storage'); $image = Image::open(public_path() . '/uploads/' . $saveName); $width = $image->width(); $max_width = $config['max_width'] ?: 750; // 图片宽度大于系统设置时才处理 $original_path = ''; if ($width > $max_width) { // 如果保留原图 if ($is_original) { $original_path = date('Ymd') .'/'. $this->buildOriginalName(); // 原图文路径 $image->save(public_path() . '/uploads/' . $original_path); } // 生成缩略图 $image->thumb($max_width, $image->height())->save(public_path() . '/uploads/'. $saveName); } return $original_path; // 注意:返回的是原图的路径 } /** * 生成原图文件名 */ private function buildOriginalName() { // 要上传图片的本地路径 $realPath = $this->file->getPathname(); // 扩展名 $ext = $this->file->getOriginalExtension(); // 自动生成文件名 return date('YmdHis') . substr(md5($realPath), 0, 6) . str_pad(rand(0, 9999), 6, '0', STR_PAD_LEFT) . ".{$ext}"; } }