接着一套增删改查之后再学习一下自定义文件上传类实现文件上传下载

  /public/uploads      文件上传位置

  /app/Org/Upload.php   自定义文件上传类

 1 <?php
 2 //自定义文件上传类
 3 namespace App\Org;
 4
 5 class Upload
 6 {
 7     public $fileInfo = null; //上传文件信息
 8     public $path;
 9     public $typeList=array();
10     public $maxSize;
11     public $saveName;
12     public $error = "未知错误!";
13
14     public function __construct($name)
15     {
16         $this->fileInfo = $_FILES[$name]; //获取上传文件信息
17     }
18
19     //执行上传
20     public function doUpload()
21     {
22         $this->path = rtrim($this->path)."/";
23
24         return $this->checkError() && $this->checkType() && $this->checkMaxSize() && $this->getName() && $this->move();
25     }
26
27     //判断上传错误号
28     private function checkError()
29     {
30         if($this->fileInfo['error']>0){
31             switch($this->fileInfo['error']){
32                 case 1: $info = "上传大小超出php.ini的配置!"; break;
33                 case 2: $info = "上传大小超出表单隐藏域大小!"; break;
34                 case 3: $info = "只有部分文件上传!"; break;
35                 case 4: $info = "没有上传文件!"; break;
36                 case 6: $info = "找不到临时存储目录!"; break;
37                 case 7: $info = "文件写入失败!"; break;
38                 default: $info = "未知错误!"; break;
39             }
40             $this->error = $info;
41             return false;
42         }
43         return true;
44     }
45     //判断上传文件类型
46     private function checkType()
47     {
48         if(count($this->typeList)>0){
49             if(!in_array($this->fileInfo['type'],$this->typeList)){
50                 $this->error = "上传文件类型错误!";
51                 return false;
52             }
53         }
54         return true;
55     }
56     //判断过滤上传文件大小
57     private function checkMaxSize()
58     {
59         if($this->maxSize>0){
60             if($this->fileInfo['size']>$this->maxSize){
61                 $this->error = "上传文件大小超出限制!";
62                 return false;
63             }
64         }
65         return true;
66     }
67
68     //随机上传文件名称
69     private function getName()
70     {
71         $ext = pathinfo($this->fileInfo['name'],PATHINFO_EXTENSION);//获取上传文件的后缀名
72         do{
73            $this->saveName = date("Ymdhis").rand(1000,9999).".".$ext;//随机一个文件名
74         }while(file_exists($this->path.$this->saveName)); //判断是否存在
75         return true;
76     }
77     //执行上传文件处理(判断加移动)
78     private function move()
79     {
80         if(is_uploaded_file($this->fileInfo['tmp_name'])){
81             if(move_uploaded_file($this->fileInfo['tmp_name'],$this->path.$this->saveName)){
82                 return true;
83             }else{
84                 $this->error = "移动上传文件错误!";
85             }
86         }else{
87             $this->error = "不是有效上传文件!";
88         }
89         return false;
90     }
91
92 }

View Code

  /app/Http/routes.php   路由文件

 1 <?php
 2
 3 /*
 4 |--------------------------------------------------------------------------
 5 | Application Routes
 6 |--------------------------------------------------------------------------
 7 |
 8 | Here is where you can register all of the routes for an application.
 9 | It's a breeze. Simply tell Laravel the URIs it should respond to
10 | and give it the controller to call when that URI is requested.
11 |
12 */
13
14 //新手入门--简单任务管理系统 至少需要3个路由
15 //显示所有任务的路由
16 Route::get('/', function () {
17     return view('welcome');
18 });
19
20 /*访问local.lamp149.com/hello连视图都不经过*/
21 //普通路由
22 Route::get('/hello', function () {
23     return "hello world! \n 生成url地址".url("/hello");
24 });
25
26 //demo测试路由exit
27 Route::get("demo","DemoController@index");
28 Route::get("demo/demo1","DemoController@demo1");
29
30
31 //学生信息管理路由  RESTful资源控制器
32 Route::resource("stu","StuController");
33 //文件上传
34 Route::resource("upload","UploadController");
35 //在线相册
36 Route::resource("photo","PhotoController");
37
38
39 //参数路由
40 Route::get("/demo/{id}",function($id){
41     return "参数id值:".$id;
42 });

View Code

  /app/Http/Controllers/PhotoController.php  在线相册控制器

  1 <?php
  2
  3 namespace App\Http\Controllers;
  4
  5 use App\Org\Upload;
  6 use Illuminate\Http\Request;
  7
  8 use App\Http\Requests;
  9 use App\Http\Controllers\Controller;
 10
 11 class PhotoController extends Controller
 12 {
 13     /**
 14      * Display a listing of the resource.
 15      *
 16      * @return \Illuminate\Http\Response
 17      */
 18     public function index()
 19     {
 20         $data = \DB::table("photo")->get();
 21         return view("photo/index",['list'=>$data]);
 22     }
 23
 24     /**
 25      * Show the form for creating a new resource.
 26      *
 27      * @return \Illuminate\Http\Response
 28      */
 29     public function create()
 30     {
 31         return view("photo/add");
 32     }
 33
 34     /**
 35      * Store a newly created resource in storage.
 36      *
 37      * @param  \Illuminate\Http\Request  $request
 38      * @return \Illuminate\Http\Response
 39      */
 40     public function store(Request $request)
 41     {
 42         //使用自定义文件上传类处理上传
 43         $upfile = new \App\Org\Upload("ufile");
 44         //初始化上传信息
 45         $upfile->path="./uploads/"; //上传储存路径
 46         $upfile->typeList =array("image/jpeg","image/png","image/gif"); //设置允许上传类型
 47         $upfile->maxSize =0; //允许上传大小
 48
 49         //执行文件上传
 50         $res = $upfile->doUpload();
 51         if($res){
 52
 53             $data=[
 54                 'title'=>$_POST['title'],
 55                 'name'=>$upfile->saveName,
 56                 'size'=>$_FILES['ufile']['size']
 57             ];
 58             $m = \DB::table("photo")->insertGetId($data);
 59             if($m>0){
 60                 return redirect()->action('PhotoController@index');
 61             }else{
 62                 //插入数据库失败,删除上传文件
 63                 unlink("./uploads/".$upfile->saveName);
 64             }
 65         }else{
 66             return back()->withInput();
 67         }
 68     }
 69
 70     /**
 71      * Display the specified resource.
 72      *
 73      * @param  int  $id
 74      * @return \Illuminate\Http\Response
 75      */
 76     public function show($id)
 77     {
 78         //获取下载图片的名字
 79         $name = \DB::table("photo")->where("id",$id)->value("name");
 80         //执行下载
 81         return response()->download("./uploads/{$name}");
 82
 83     }
 84
 85     /**
 86      * Show the form for editing the specified resource.
 87      *
 88      * @param  int  $id
 89      * @return \Illuminate\Http\Response
 90      */
 91     public function edit($id)
 92     {
 93         //根据ID获取照片详细信息
 94         $data = \DB::table("photo")->where("id",$id)->first();
 95         return view("photo/edit",['list'=>$data]);
 96     }
 97
 98     /**
 99      * Update the specified resource in storage.
100      *
101      * @param  \Illuminate\Http\Request  $request
102      * @param  int  $id
103      * @return \Illuminate\Http\Response
104      */
105     public function update(Request $request, $id)
106     {
107         //使用自定义文件上传类处理上传
108         $upfile = new \App\Org\Upload("ufile");
109         //初始化上传信息
110         $upfile->path="./uploads/"; //上传储存路径
111         $upfile->typeList =array("image/jpeg","image/png","image/gif"); //设置允许上传类型
112         $upfile->maxSize =0; //允许上传大小
113
114         //执行文件上传
115         $res = $upfile->doUpload();
116         if($res){
117
118             $data=[
119                 'title'=>$_POST['title'],
120                 'name'=>$upfile->saveName,
121                 'size'=>$_FILES['ufile']['size']
122             ];
123             //上传成功修改数据库
124             $m = \DB::table("photo")->where("id",$id)
125                                     ->update($data);
126             if($m>0){
127                 //修改数据库成功删除原图片
128                 unlink("./uploads/".$_POST['img']);
129                 return redirect()->action('PhotoController@index');
130             }else{
131                 //修改失败,删除上传图片
132                 unlink("./uploads/".$upfile->saveName);
133             }
134         }else{
135             //上传文件失败
136             //哪来哪回
137             return back()->withInput();
138         }
139
140     }
141
142     /**
143      * Remove the specified resource from storage.
144      *
145      * @param  int  $id
146      * @return \Illuminate\Http\Response
147      */
148     public function destroy(Request $request, $id)
149     {
150         $m = \DB::table("photo")->delete($id);
151         if($m>0){
152             unlink("./uploads/{$request->pname}");
153             return redirect()->action('PhotoController@index');
154         }else{
155             return redirect()->action('PhotoController@index');
156         }
157
158     }
159 }

View Code

  /resources/views/photo    在线相册视图模板目录

index.blade.php

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8"/>
 5     <title>Laravel--在线相册</title>
 6
 7 </head>
 8 <body>
 9 <center>
10
11     @include("photo.menu")
12     <h3>浏览学生信息</h3>
13         <table width="700" border="1">
14             <tr>
15                 <th>编号</th>
16                 <th>标题</th>
17                 <th>图片</th>
18                 <th>大小</th>
19                 <th>操作</th>
20             </tr>
21             @foreach($list as $pic)
22                 <tr align="center">
23                     <td>{{$pic->id}}</td>
24                     <td>{{$pic->title}}</td>
25                     {{-- 相对路径 --}}
26                     <td><img src="./uploads/{{$pic->name}}" width="200"></td>
27                     <td>{{$pic->size}}</td>
28                     <td>
29                         <a href="javascript:void(0)" οnclick="doDel({{$pic->id.',"'.$pic->name.'"'}})">删除</a>
30                         <a href="{{url("photo")."/".$pic->id."/edit"}}">编辑</a>
31                         <a href="{{url("photo")."/".$pic->id}}">下载</a></td>
32                 </tr>
33             @endforeach
34         </table>
35     <form action="" method="POST">
36         <input type="hidden" name="_method" value="DELETE">
37         <input type="hidden" name="_token" value="{{ csrf_token() }}">
38         <input type="hidden" name="pname" value="" id="pname">
39     </form>
40     <script>
41         function doDel(id,name){
42             var form =  document.getElementsByTagName("form")[0];
43             var pname = document.getElementById("pname");
44             pname.value = name;
45             form.action ="{{url('photo')}}"+"/"+id;
46             form.submit();
47         }
48     </script>
49 </center>
50 </body>
51 </html>

View Code

menu.blade.php

1 <h2>Laravel实例--在线相册</h2>
2 <a href="{{url('photo')}}">浏览信息</a> |
3 <a href="{{url('photo/create')}}">添加信息</a>
4 <hr/>

View Code

add.blade.php

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8"/>
 5     <title>Laravel实例--在线相册</title>
 6 </head>
 7 <body>
 8 <center>
 9     @include("photo.menu")
10     <h3>添加相片</h3>
11     <form action="{{url('photo')}}" method="post" enctype="multipart/form-data">
12         <input type="hidden" name="_token" value="{{ csrf_token() }}">
13         <table width="300" border="0">
14             <tr>
15                 <td align="right">标题:</td>
16                 <td><input type="text" name="title"/></td>
17             </tr>
18             <tr>
19                 <td align="right">相片:</td>
20                 <td><input type="file"  name="ufile" /></td>
21             </tr>
22             <tr>
23                 <td colspan="2" align="center">
24                     <input type="submit" value="添加"/>
25                     <input type="reset" value="重置"/>
26                 </td>
27             </tr>
28         </table>
29     </form>
30 </center>
31 </body>
32 </html>

View Code

edit.blade.php

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8"/>
 5     <title>学生信息管理</title>
 6 </head>
 7 <body>
 8 <center>
 9     @include("photo.menu")
10
11     <h3>编辑学生信息</h3>
12     <form action="{{url('photo')."/".$list->id}}" method="post" enctype="multipart/form-data">
13         <input type="hidden" name="_method" value="PUT">
14         <input type="hidden" name="_token" value="{{ csrf_token() }}">
15
16         <table width="280" border="0">
17             <tr>
18                 <td  align="right">标题:</td>
19                 <td><input type="text" name="title" value="{{$list->title}}"/></td>
20             </tr>
21             <tr>
22                 <td align="right">图片:</td>
23                 {{--绝对路径--}}
24                 <td><img src="{{url('uploads/'.$list->name)}}" width="200">
25                     <input type="hidden" name="img" value="{{$list->name}}">
26                     <input type="file" name="ufile"></td>
27             </tr>
28             <tr>
29                 <td colspan="2" align="center">
30                     <input type="submit" value="修改"/>
31                     <input type="reset" value="重置"/>
32                 </td>
33             </tr>
34         </table>
35     </form>
36 </center>
37
38 </body>
39 </html>

View Code

修改入口模板/resources/views/welcome.blade.php

 1 <html>
 2     <head>
 3         <title>Laravel--实例</title>
 4     </head>
 5     <style>
 6         a{
 7
 8             text-decoration: none;
 9         }
10     </style>
11     <body>
12         <div class="container" style="width:500px;margin: auto;">
13             <div class="content">
14                 <div class="title"><h1>Laravel 5.1 实例</h1></div>
15                 <div style="width:250px;text-align: center;">
16                     <h3><a href="{{url('stu')}}">1. 学生信息管理</a></h3>
17                     <h3><a href="{{url('upload')}}">2. 文件上传</a></h3>
18                     <h3><a href="{{url('photo')}}">3. 在线相册</a></h3>
19                 </div>
20             </div>
21         </div>
22     </body>
23 </html>

View Code

转载于:https://www.cnblogs.com/yexiang520/p/5777838.html

laravel框架学习(三)相关推荐

  1. laravel database.php,php Laravel框架学习(一) 之 建立数据库并填充测试数据

    php Laravel框架学习(一) php Laravel框架学习之Laravel 建立数据库并填充测试数据 建立数据库 前面我们已经明确目标网站的基本功能,现在我们先来建立它的数据库. 设计数据库 ...

  2. PyTorch框架学习三——张量操作

    PyTorch框架学习三--张量操作 一.拼接 1.torch.cat() 2.torch.stack() 二.切分 1.torch.chunk() 2.torch.split() 三.索引 1.to ...

  3. Laravel框架学习

    前言: 首先,了解 Laravel 的核心概念是非常重要的.Laravel 使用了现代化的 MVC(模型-视图-控制器)架构模式,这有助于将代码逻辑分离,提高应用的可维护性和可扩展性.同时,Larav ...

  4. Laravel框架学习笔记(一)——phpstudy下的安装配置

    2019独角兽企业重金招聘Python工程师标准>>> 网上关于如何安装laravel框架的教程很多,就不多说了,推荐大家去看http://www.golaravel.com/里的教 ...

  5. php laravel 教程,Laravel框架学习之新手教程

    本篇文章主要讲述了新手学习laravel的过程中必须要了解的事项,具有一定的参考价值准备学习laravel框架的朋友一定不能错过哦,希望看完能对你有所帮助. 一.Laravel环境搭建 1.windo ...

  6. laravel框架学习之路(一)前后台用户认证分离

    准备工作: 1.下载laravel框架 2.配置好项目(数据库连接以及虚拟主机) 开始: 前台用户认证laravel已经为我们写好了,此部分可参考官方文档 创建模型(以adminstrator为例) ...

  7. Laravel框架学习 -- php artisan down/up

    为什么80%的码农都做不了架构师?>>>    由于某种原因,公司整体框架由python的flask框架,转换为php的laravel.在断断续续几个月的时间里,边继续写着flask ...

  8. [Laravel框架学习一]:Laravel框架的安装以及 Composer的安装

    1.先下载Composer-Setup.exe,下载地址:下载Composer .会自动搜索PHP.exe的安装路径,如果没有,就手动找到php路径下的php.exe. 2.在PHP目录下,打开php ...

  9. ExtJs UI框架学习三

    JavaScript 面向对象及设计模式系列--灵活的JavaScript,Timo.Lee 当前,Javascript已经成为世界上最受欢迎和被广泛应用的的编程语言--因为他被捆绑到各种浏览器中.作 ...

最新文章

  1. mysql 月份差_MySQL时间差返回月个数
  2. 『Numpy』常用方法记录
  3. c语言r5够用吗,泡菜说 普通人有必要买R5吗?
  4. Brocade NOS学习笔记(第一章——第三章)
  5. 请求参数绑定实体类型
  6. 当你辛辛苦苦写的博客文章被无情复制,成为了他的原创,你作何感想?
  7. python自动化测试脚本可以测php吗_python unittest实现api自动化测试_python
  8. git小技巧之分支、关联远程仓库、回滚、解决.gitignore不生效等
  9. shell 脚本初习
  10. 突发:格鲁吉亚所有公民的个人详情被泄露在黑客论坛
  11. 关于解决“用系统U盘安装win7却提示‘缺少所需的CD/DVD驱动器设备驱动程序’”的问题
  12. Qt与VS2005/2008的完美配合(转)
  13. C# action 返回值_C#知识点讲解之C#delegate、event、Action、EventHandler的使用和区别
  14. 如何在没有域的环境中搭建AlwaysOn(一)
  15. 国内从事CV相关的企业
  16. c语言一本书的页码从自然数1开始顺序编码,C++_关于统计数字问题的算法,一本书的页码从自然数1开始顺 - phpStudy...
  17. SDN入门第五篇——交换机与控制器之间的交互流程
  18. js写的 几款时间轴
  19. 什么样的互联网创业者不靠谱?
  20. 凌晨3点不回家,你不要老婆孩子了?

热门文章

  1. 各种同步方法性能比较(synchronized,ReentrantLock,Atomic)
  2. sqlserver2005 openRowSet 和row_Number
  3. winform listbox 没有listitem的问题
  4. ContentServer迁移的几个步骤
  5. python中ndarray除_Numpy 基本除法运算和模运算
  6. python xlrd模块_Python中xlrd模块解析
  7. GDAL插值使用示例
  8. android点击图片跳转页面底部,【报Bug】安卓底部选项卡webview模式下 点击跳转到某个页面后,会出现底部重叠的问题...
  9. Cocos Creator 使用 Android Studio 打包 APK 遇到的坑
  10. 使用CSS 媒体查询功能满足不同屏幕分辨率要求