PHP Laravel 上传图片、文件等类封装

今天把项目中上传功能封装成类,方便后面使用,简单的封装了一下,感觉还不怎么好,后面继续优化。

具体代码如下:

rush:PHP;"> 3*1024*1024,//上传文件大小限制 (0-不做限制) 'exts' => array('jpg','jpeg','gif','png','doc','docx','xls','xlsx','ppt','pptx','pdf','rar','zip'),//允许上传文件后缀 'subName' => '',//子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组 'rootPath' => '/uploads/',//保存根路径 'savePath' => '',//保存路径 'thumb' => array(),//是裁剪压缩比例 ); public function __construct($config = array()){ /* 获取配置 */ $this->config = array_merge($this->config,$config); if(!emptyempty($this->config['exts'])){ if (is_string($this->exts)){ $this->config['exts'] = explode(',',$this->exts); } $this->config['exts'] = array_map('strtolower',$this->exts); } $this->config['subName'] = $this->subName ? ltrim($this->subName,'/') : '/'.date('Ymd'); $this->fullPath = rtrim(public_path(),'/').$this->config['rootPath']; } public function __get($name) { return $this->config[$name]; } public function __set($name,$value){ if(isset($this->config[$name])) { $this->config[$name] = $value; } } public function __isset($name){ return isset($this->config[$name]); } /** * 获取最后一次上传错误信息 * @return string 错误信息 */ public function getError(){ return $this->error; } public function upload($file){ if(emptyempty($file)){ $this->error = '没有上传文件'; return false; } if(!$this->checkRootPath($this->fullPath)){ $this->error = $this->getError(); return false; } $fileSavePath=$this->fullPath.$this->savePath.$this->subName; if(!$this->checkSavePath($fileSavePath)){ $this->error = $this->getError(); return false; } $files =array(); if(!is_array($file)){ //如果不是数组转成数组 $files[]=$file; }else{ $files=$file; } $info = array(); $imgThumb = new \App\ThinkClass\ThumbClass(); foreach ($files as $key=>$f){ $this->file=$f; $f->ext = strtolower($f->getClientOriginalExtension()); /*文件上传检查*/ if (!$this->check($f)){ continue; } $fileName = str_random(12).'.'.$f->ext; /* 保存文件 并记录保存成功的文件 */ if ($this->file->move($fileSavePath,$fileName)) { /*图片按照宽高比例压缩*/ \Log::notice($fileSavePath.$fileName); if(!emptyempty($this->thumb) && is_array($this->thumb)){ $imgThumb ->thumb($this->thumb,$fileSavePath.'/'.$fileName); } $info[]=$this->rootPath.$this->savePath.$this->subName.'/'.$fileName; } } return is_array($info) ? $info : false; } /** * 检测上传根目录 * @param string $rootpath 根目录 * @return boolean true-检测通过,false-检测失败 */ protected function checkRootPath($rootpath){ if(!(is_dir($rootpath) && is_writable($rootpath))){ $this->error = '上传根目录不存在!'; return false; } return true; } /** * 检测上传目录 * @param string $savepath 上传目录 * @return boolean 检测结果,true-通过,false-失败 */ public function checkSavePath($savepath){ /* 检测并创建目录 */ if (!$this->mkdir($savepath )) { return false; } else { /* 检测目录是否可写 */ if (!is_writable($savepath)) { $this->error = '上传目录不可写!'; return false; } else { return true; } } } /** * 检查上传文件 * @param array $file 文件信息 */ private function check($file) { /* 检查文件大小 */ if (!$this->checkSize($file->getSize())) { $this->error = '上传文件大小不符!'; return false; } /* 检查文件后缀 */ if (!$this->checkExt($file->ext)) { $this->error = '上传文件后缀不允许'; return false; } /* 通过检测 */ return true; } /** * 检查文件大小是否合法 * @param integer $size 数据 */ private function checkSize($size) { return !($size > $this->maxSize) || (0 == $this->maxSize); } /** * 检查上传文件后缀是否合法 * @param string $ext 后缀 */ private function checkExt($ext) { return emptyempty($this->config['exts']) ? true : in_array(strtolower($ext),$this->exts); } /** * 创建目录 * @param string $savepath 要创建的穆里 * @return boolean 创建状态,true-成功,false-失败 */ protected function mkdir($savepath){ if(is_dir($savepath)){ return true; } if(mkdir($savepath,0777,true)){ return true; } else { $this->error = "目录创建失败"; return false; } } }

使用案例:

头部引用 use App\ThinkClass\UploadClass;

exts=array('jpg','png'); $upload->maxSize=5*1024*1024; $upload->savePath='course/uid_6'; $file = $request->file('fileImg'); $aa = $upload->upload($file); dd($aa);

总结

以上所述是小编给大家介绍的PHP Laravel 上传图片文件等类封装,希望对大家有所帮助。程序员遇到问题都会上(编程之家jb51.cc)查找问题解答方法!如果觉得站点还不错,随手转发给程序员朋友一下!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


今天windows 之家小编给大家介绍下在windows 中使用laravel安装homestead的操作方法!安装及配置:安装使用Vagrant安装Homestead盒子安装 Homestead配置 Homestead设置 Provider配置共享文件夹配置 Nginx 站点Hosts文件启动 Vagrant Box可
我有一个网站,包括2个不同的登录表单,2个位置,一个在导航栏上,另一个是登录页面,将在系统捕获未登记的访问者时使用.我可以问一下我在LoginRequest.php中做错了什么,如果登录过程中出现任何类型的错误,我会设置一个重定向到自定义登录页面的条件?我的代码如下:<?phpnamespaceApp
这是我用于上传多个文件的控制器代码,我从GoogleChrome上的’postman’restAPI客户端传递密钥和值.我正在从邮递员添加多个文件,但只有1个文件正在上传.publicfunctionpost_files(){$allowedExts=array("gif","jpeg","jpg","png","txt","pdf","doc
1. 只需要在 config\app.php 文件中加入 faker_locale=>'zh_CN' ,可生成部分中文数据,如nameaddress 等 2. 时间生成,当月随机时间$faker->dateTimeThisMonth()3. 随机数rand(1,5)'id'=>$faker->randomElement(['1','2','3'])
我正在尝试运行迁移(见下文)并为数据库播种,但是当我运行时phpartisanmigrate--seed我收到此错误:Migrationtablecreatedsuccessfully.Migrated:2015_06_17_100000_create_users_tableMigrated:2015_06_17_200000_create_password_resets_tableMigrated:2015_06_1
我正在尝试获取所有模型的关联数组.我有以下型号:classArticleextendsEloquent{protected$guarded=array();publicstatic$rules=array();publicfunctionauthor(){return$this->belongsTo('Author');}publicfunctionc
我有一个包含以下表和关系的数据库:租房广告1-1Carm-1型号m-1品牌如果我想要检索广告,我可以简单地使用:Advert::find(1);如果我想要汽车的细节,我可以使用:Advert::find(1)->with('Car');但是,如果我还想要模型的细节(跟随与Car的关系),语法是什么,以下不起作用:Advert:
在5.3之前的Laravel项目中,我使用脚本标记使用了Vue.js,如下所示:<scripttype="text/javascript"src="../js/vue.js"></script>然后我会创建一个特定于该页面的Vue实例,如下所示:<script>newVue({el:'#app',data:{message:&#03
我似乎不明白为什么我们需要运行一个带有phpartisan服务的Laravel应用程序而不是用Apache或nginx运行它.我知道在开发过程中,我们使用artisan来启动站点,在部署到服务器之后,您使用Web服务器来加载站点.什么是首先在工匠中运行应用程序的用途?解决方法:serve命令只是PHPBuilt-in
我已经设置了以下Laravel命令:protectedfunctionschedule(Schedule$schedule){$schedule->command('command:daily-reset')->daily();$schedule->command('command:monthly-reset')->monthly();}然后,在我的服务器上,我已经设置了一个cron作业,
所以我向reviewsController@export发了一个小的ajax请求.现在当我在console.log()成功方法中的数据时,ajax响应显示正确的数据.但是我的CSV尚未下载.所以我拥有所有正确的信息并且基本上创建了csv.我认为这可能与设置标题有关吗?publicfunctionexport(){header("Conte
我之前没有遇到过这个问题,但是我的php工匠修补程序因发出任何命令而崩溃–并且没有留下任何导致崩溃的日志.project4$phpartisantinkerPsyShellv0.9.9(PHP7.3.0—cli)byJustinHileman>>>use\App\Jobs\testJob;project4$甚至是最简单的命令:project4$php
在进行laravel迁移时,我面临一些小小的不便.我使用Laravel5.1.由于存在许多具有许多关系的表,因此我可能无法重命名迁移文件,因此它们以正确的顺序运行,因此不会违反外键约束.这就是我过去做过的事情,而且非常不实用.我现在正在做的是定义每个迁移,如下所示:classCreateSomeTa
当我运行它输出:phpartisanserve--port=80Laraveldevelopmentserverstartedonhttp://localhost:80如何让它在后台运行,当我退出控制台时服务器停止.解决方法:简短的回答:不要Web服务器工匠使用的是PHP内置Web服务器,它不适用于除了开发之外的任何场景,如Built-inwebs
我仔细阅读并重新阅读了Vuedocs“ReactivityinDepth”以及vm.$set和Vue.set的API,但我仍然很难确定何时使用哪个.我能够区分这两者是很重要的,因为在我目前的Laravel项目中,我们动态地在对象上设置了很多属性.文档中的区别似乎是vm.$set为“ForVueinstance”的语言,而Vue.se
我一直试图从上传的文件中获取扩展名,在谷歌搜索,我没有得到任何结果.该文件已存在于路径中:\Storage::get('/uploads/categories/featured_image.jpg);现在,我如何获得上述文件的扩展名?使用输入字段我可以像这样获得扩展:Input::file('thumb')->getClientOriginalExtension(
我正在尝试使用信息https://github.comrk/predis连接到具有predis1.1和SSL的Redis,其中在示例中使用以下配置://Namedarrayofconnectionparameters:$client=newPredis\Client(['scheme'=>'tls','ssl'=>['cafile'=>'p
根据Laravel4documentation.作曲家是:Viewcomposersarecallbacksorclassmethodsthatarecalledwhenaviewisrendered.Ifyouhavedatathatyouwantboundtoagivenvieweachtimethatviewisrenderedthroughoutyourapplication,aviewcomposercan
是否可以手动注册用户(与工匠?)而不是通过身份验证注册页面?我只需要一些用户帐户,并想知道是否有办法创建这些帐户而无需设置注册控制器和视图.解决方法:我想你想一次性这样做,所以不需要像创造一个Artisan命令那样花哨的东西等等.我建议简单地使用phpartisantinker(很棒的工具!)
所以我的迁移文件夹看起来像这样,因为我有几十个表,它保持组织和清洁:migrations/create_user_table.phprelations/translations/我正在尝试刷新所有迁移和种子,但似乎我遇到了轻微的打嗝,我不知道artisan命令以递归方式运行迁移(即在关系和翻译文件夹中运行迁移).我