laravel图片上传

其实我也是一个新手,关于用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" );
}
}
}

先判断数据库里是否有图片,没有就显示一张默认的图片,有就读取图片的名字、路径、以及图片的格式,然后根据图片的路径显示图片。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值