• laravel框架学习(三)


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

      /public/uploads      文件上传位置

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

     1 <?php
     2 //自定义文件上传类
     3 namespace AppOrg;
     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! 
     生成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 AppHttpControllers;
      4 
      5 use AppOrgUpload;
      6 use IlluminateHttpRequest;
      7 
      8 use AppHttpRequests;
      9 use AppHttpControllersController;
     10 
     11 class PhotoController extends Controller
     12 {
     13     /**
     14      * Display a listing of the resource.
     15      *
     16      * @return IlluminateHttpResponse
     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 IlluminateHttpResponse
     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  IlluminateHttpRequest  $request
     38      * @return IlluminateHttpResponse
     39      */
     40     public function store(Request $request)
     41     {
     42         //使用自定义文件上传类处理上传
     43         $upfile = new AppOrgUpload("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 IlluminateHttpResponse
     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 IlluminateHttpResponse
     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  IlluminateHttpRequest  $request
    102      * @param  int  $id
    103      * @return IlluminateHttpResponse
    104      */
    105     public function update(Request $request, $id)
    106     {
    107         //使用自定义文件上传类处理上传
    108         $upfile = new AppOrgUpload("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 IlluminateHttpResponse
    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)" 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>
    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="500px;margin: auto;">
    13             <div class="content">
    14                 <div class="title"><h1>Laravel 5.1 实例</h1></div>
    15                 <div style="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
  • 相关阅读:
    聊聊MySQL的索引吧
    污力满满的技术解读,瞬间印象深刻
    lua语言(1):安装、基本结构、函数、输入输出
    pandas中的那些让人有点懵逼的异常(坑向)
    与分布式相关的面试题
    图解IP基础知识
    Date类
    String 与StringBuffer习题
    Java的常用类 String
    线程练习题
  • 原文地址:https://www.cnblogs.com/yexiang520/p/5777838.html
Copyright © 2020-2023  润新知