其实我也是一个新手,关于用laravel实现图片上传,也是学习了很久。
第一 关于路由
Route::get('pict','PicController@index'); Route::post('file','PicController@store'); Route::get('p','PicController@readpict');
第二个路由是图片上传,第三个路由是图片读取。
第二 关于控制器上传图片
//上传图片public function store(){ob_end_clean ();header ( "Content-Type: text/html; charset=utf-8" );$data =[];if (!request:: hasFile ( 'photo' )){$requsetJson = array ("state" => "field" ,);$data [ "status" ]= false ;$data [ "requestJson" ]= $requsetJson ;return $data ;} else {$file =Request:: file ( 'photo' );//文件的名字$fileName = $file ->getClientOriginalName();$storage_path =config( "my_config.image_upload_dir" ).session( "user.user_id" ). "/" ;//dd($storage_path);//存储文件的绝对路径$path = $_SERVER [ 'DOCUMENT_ROOT' ]. $storage_path ; //根目录// dd($path);$name = date ( 'YmdHis' ).session( "user.user_id" ). rand ( 1000 , 9999 ). "." . $file ->getClientOriginalExtension(); //生成路径// dd($name);$file ->move( $path , $name ); //移动$input_data [ "picture_name" ]= $storage_path . $name ;$input_data [ "picture_format" ]= $file ->getClientOriginalExtension();if ( $id =DB:: table ( "picture" )->insertGetId( $input_data )){$requsetJson = array ("state" => "SUCCESS" ,"url" =>config( "my_config.website_url" ). "/getImage/" . $id ,"title" => $id ,"original" => "" ,"type" => "." . $file ->getClientOriginalExtension(),"size" => $file ->getClientSize());$data [ "status" ]= true ;$data [ "requestJson" ]= $requsetJson ;return $data ;} else {$requsetJson = array ("state" => "插入数据库失败");$data [ "status" ]= false ;$data [ "requestJson" ]= $requsetJson ;return $data ;}}}
对于上传的图片先对其名字进行处理,然后再通过move函数移动上传的图片到对应的项目的位置,最后在把文件的名字上传到数据库,并返回上传状态。
第三 关于控制器读取数据
public function readpict( $image_id = 2 ){if ( $image_id == 0 ){header ( "Content-type:image/jpeg" ); //表明请求页面的内容是jpeg格式的图像readfile ( $_SERVER [ "DOCUMENT_ROOT" ]. "/pic/1.jpg" );}$imageData =DB:: table ( "picture" )->where( "picture_id" , "=" , $image_id )->first();// dd($imageData);if ( $imageData != NULL ){$path = $imageData -> picture_name ;$format = $imageData -> picture_format ;switch ( $format ){case "gif" : $ctype = "image/gif" ; break ;case "png" : $ctype = "image/png" ; break ;case "jpeg" :case "jpg" : $ctype = "image/jpeg" ; break ;default : $ctype = "image/jpeg" ;}header ( "Content-type:" . $ctype );readfile ( $_SERVER [ "DOCUMENT_ROOT" ]. "/pic/1.jpg" );} else {header ( "Content-type:image/jpeg" );readfile ( $_SERVER [ "DOCUMENT_ROOT" ]. "/pic/1.jpg" );}}}
先判断数据库里是否有图片,没有就显示一张默认的图片,有就读取图片的名字、路径、以及图片的格式,然后根据图片的路径显示图片。