laravel框架学习(三)

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

  /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 }

  /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","[email protected]");
28 Route::get("demo/demo1","[email protected]");
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 });

  /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(‘[email protected]‘);
 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(‘[email protected]‘);
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(‘[email protected]‘);
154         }else{
155             return redirect()->action(‘[email protected]‘);
156         }
157
158     }
159 }

  /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)" onclick="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>

menu.blade.php

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

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>

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>

修改入口模板/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>

时间: 2024-12-16 23:48:47

laravel框架学习(三)的相关文章

Struts2框架学习(三) 数据处理

Struts2框架学习(三) 数据处理 Struts2框架框架使用OGNL语言和值栈技术实现数据的流转处理. 值栈就相当于一个容器,用来存放数据,而OGNL是一种快速查询数据的语言. 值栈:ValueStack一种数据结构,操作数据的方式为:先进后出 OGNL : Object-GraphNavigation Language(对象图形导航语言)将多个对象的关系使用一种树形的结构展现出来,更像一个图形,那么如果需要对树形结构的节点数据进行操作,那么可以使用 对象.属性 的方式进行操作,OGNL技

Laravel框架学习(四)

一. composer的安装: 1.Composer是什么? 是 PHP 用来管理依赖(dependency)关系的工具. 你可以在自己的项目中声明所依赖的外部工具库(libraries), Composer 会帮你安装这些依赖的库文件. 2.网址:https://getcomposer.org 下载:https://getcomposer.org/download/ 中国全量镜像:http://pkg.phpcomposer.com/ 启用本镜像服务命令: composer config -g

laravel框架学习(二)

在了解Laravel框架的基本结构之后,初步认识访问过程中路由的使用方法,以一套基本的学生信息增删改查来迅速学习框架开发. 首先了解几个目录文件作为开发的主要阵地: 1. /app/Http/routes.php 路由文件,一切访问从路由开始 2./app/Http/Controllers 控制器目录,我们写的控制器都放在该目录下 3./app/config Laravel配置文件夹一般修改.env文件 4./.env 经常修改配置的文件,数据库配置就在这里 5./public Laravel框

laravel框架学习(一)

一.初识Laravel 1.百科形容:Laravel是一套简洁.优雅的PHP Web开发框架(PHP Web Framework). 2.资料来源:官方网址http://www.golaravel.com/ Laravel学院:http://laravelacademy.org/ 3.搭建一个自己的Laravel框架 Laravel 利用 Composer(Composer 中文)来管理其自身的依赖包.因此,在使用 Laravel 之前,请务必确保在你的机器上已经安装了 Composer (1)

Laravel框架学习 -- 安装

环境:mac os  10.10.5; php 5.6.9; 文档参考: http://www.golaravel.com/ 包管理: python  一般使用 pip Laravel 利用 Composer(Composer 中文)来管理其自身的依赖包. 安装: [email protected]:/Users/lpe234  $ brew tap josegonzalez/homebrew-php Warning: Already tapped! [email protected]:/Use

Laravel 框架学习笔记

Laravel 框架使用 首先是安装,按步骤来吧 1.Apache+PHP+Mysql    这些不用说,你可以用wamp   ,不过我这里用的是phpstudy,因为Laravel 要用到的php版本比较高,我用的是5.5的版本. 2.composer 安装包    Windows安装工具   安装的时候要确保 OpenSSL PHP 扩展打开  对应php版本 3.Git 安装包     网上自己找一个   下载安装好 4.下载一个Laravel的版本,网上找的   https://gith

Android 学习笔记之AndBase框架学习(三) 使用封装好的函数完成Http请求..

PS:踏踏实实走好每一步... 学习内容: 1.使用AndBase框架实现无参Http Get请求... 2.使用AndBase框架实现有参Http Post请求... 3.使用AndBase框架实现有参Http Get请求...   AndBase框架为我们提供了一些相关的方法提供给我们使用,用来完成Http网络请求...总体就是对Http请求的一个封装,不过个人认为,网络请求这一模块更加推荐使用Volley框架..楼主对比了两个框架中的源码...Volley更多的地方是使用抽象方法封装在接口

php laravel框架学习笔记 (一) 基本工作原理

原博客链接:http://www.cnblogs.com/bitch1319453/ 安装laraver完成后,在cmd中进入laravel目录,使用命令php artisan serve开启8000端口服务器 然后简单介绍一下laraver的工作流程.这个工作流程包含了页面编写以及传递参数,可以进行一些基本工作了 开始页面 与其他框架不同的是,框架中有一个route选项.打开app/http/request/route.php,你将看到 <?php /*|-------------------

laravel框架学习

在聊技术之前,我们首先谈谈研究生的生活现状.进入到研究生忙碌的生活中,研究生是这么一个群体,外界对研究生的爱称是"研究僧",为什么我自己会觉得会是爱称.因为研究僧说的是研究生对自己的学业比较的刻苦.对自己的领域充满思考,他们思考着人类发展到今天出现的问题,以及未来人类的发展.他们怀着希望,积极的投身到的领域的建设中去.不管是怎么样,他们都是研究僧.我进入到研究生的生活时,并没有直接接触到什么项目,而我的老师先是让我明白自己的头衔"研究生".现在的社会功利心很强.不是