laravel-request

laravel的请求:

请求的使用一般是在控制器方法的参数列表中进行依赖注入,从而就可以在方法中使用请求实例了,通过请求实例可以对用户的请求进行解析从而达到进一步的处理:

比如:

  • 获取get请求的某个参数啦
  • 获取所有get的请求对应的数组啦
  • 获取文件上传的请求啦,之后对文件进行存储的操作啦
  • 获取请求对应的方法啦
  • 获取请求是否为某个方法啦
  • 获取请求所带来的cookie啦
  • and so on

-------------------------------------一个实例-------------------------------------------------------------

use Illuminate\Http\Request; // 至少引入此类

index(Request $request){ //在函数的参数列表中进行依赖注入

  //对用户请求做一些处理

  $request->haoduorequestinstancedemethod();

}

 

 

-----------------------------------常用的方法,而不是全部的方法--------------------------------------------

    request的方法             描述       
input('key','default-value') 此方法可以获取get请求所带来的特定参数的值,如果没有该参数可以提供默认值
all() 此方法获取get请求的所有参数,然后会返回一个数组,一个键值对数组
path() 对于http://localhost/test?b=37521请求,会返回'test' 仅仅是个‘路径’
url() 对于http://localhost/test?b=37521请求,会返回'http://localhost/test',也就是说,url不带参数
isMethod('GET') 判断请求的方式,返回值为布尔值
getMethod() 获取请求方式,返回为字符串
is()  
cookie('key','default-value') 从请求实例中拿取某个cookie,如果没有则会返回默认的值
hasFile('file') 参数'file'是上传文件时候的name='file',通过此方法判断上传文件时候是否真的选择了待上传的文件
file('file') 通过此方法获取上传的文件,对该函数的返回值进行判断无误后应该处理如何保存文件到对应的位置

 

 

 

 

 

 

 

 

 

 

--------------------------------------------------文件上传实例----------------------------------------------------------------

1.新建一个控制器,具体代码如下

2.配置路由(在文件app\Http\routes.php):Route::controller('file','FileUploadController');

 

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;//引入请求类
use App\Http\Controllers\Controller;//引入控制器基类
class FileUploadController extends Controller{

public function getForm(){
   $csrf_field = csrf_field();//laravel的post请求要通过csrf验证
   $post_url = '/file/upload';//对应下面的那个方法postUpload(),前面的file是因为在路由的时候配置的
   $text=<<<T
     <form action="$post_url" method="POST" enctype="multipart/form-data">
       选择文件<input type='file' name='file'><br>
       $csrf_field
       <input type='submit' name='上传'>
     </form>
T;
   return $text;

}

public function postUpload(Request $request){
  if(!$request->hasFile('file')){
    exit('你还没有选择文件');
  }

 $file = $request->file('file');
 if(!$file->isValid()){
   exit('somethings is wrong!');
 }

// $destPath = realpath(public_path('docs'));
// if(!file_exists($destPath))
// mkdir($destPath,0755,true);

 $filename = $file->getClientOriginalName();
 if(!$file->move('/',$filename)){
  exit('error when save');
 }else{
  exit('saved');
 }
}

 

-----------------------------------That's all----------------------------------------------------------------

 

posted on 2017-03-10 12:20  blbl9527  阅读(1073)  评论(0)    收藏  举报

导航


github sina微博 FB