THINKPHP把上传文件独立到项目外面防止脚本更新覆盖文件库的实现方式 # 背景 公司部署有一套脚本实现,但是由于以前把上传的文件放置在项目中(/public/uploads),随着项目的日积月累,上传的文件库越来越大,每次部署脚本都需要把这个上传库做一次备份,然后部署后重新移入项目内,这样不但使脚本运行超慢,而且风险很大,因为中间就出现过脚本出错把图片库直接干掉的情况。 为了针对这种情况,希望程序实现上传库独立于项目,项目的部署无需操作上传库,而且多个项目之间可以统一使用一个上传库,方便管理。 PS:为什么不使用OSS?没钱。 # 实现 首先在配置文件设定好图片头绝对路径,以及新增一个静态库的专属域名。 注意绝对路径win下与linux下不同。 ```php 'app_img_root' => "http://static.app/chenls",//Request::instance()->domain() 'app_file_path' => 'D:\www\static\chenls',///var/www/static/teanet ``` ```php /** * @authority 上传图片 */ public function uploadImg(){ $Attachment = model('Attachment'); $file = request()->file('image'); if(empty($file) || !in_array(input('type'), array('fields'))){ return $this->err('参数错误!'); } $size = $file->getSize(); $valid['size'] = 2097152;//2M $valid['ext'] = 'jpg,png,gif'; $path = config('APP_FILE_PATH').'http://static.chenls.me/chenls/uploads/'.input('type').'/';//绝对路径 $info = $file->validate($valid)->rule('date')->move($path); if($info){ $fileUrl = $path.$info->getSaveName(); $reback['url'] = str_replace(config('APP_FILE_PATH'),"",$fileUrl);//保存的时候去掉绝对路径 return $this->suc($reback); }else{ return $this->err($file->getError()); } } ``` 这样在程序展示图片时候,拿到数据库的数据后需要拼接上图片域,这样图片就能正常展示了。