本文实例讲述了laravel5.5框架的上传图片功能。分享给大家供大家参考,具体如下:
这里面包含单张和多张图片的上传
首先先来前端页面的html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!DOCTYPE html> < html > < head > < title >上传图片</ title > </ head > < body > < form method = "post" action = "{{url('uploadImgs')}}" enctype = "multipart/form-data" > {{csrf_field()}} < input type = "file" name = "filename[]" >< br /> < input type = "file" name = "filename[]" >< br /> < input type = "file" name = "filename[]" > < button type = "submit" >上传图片</ button > </ form > </ body > |
记得路径那改成post
然后就是后台代码
到config/filesystem.php下增加一个
1
2
3
4
|
'upload' => [ 'driver' => 'local' , 'root' => 'uploadImages' ], |
1
|
use Illuminate\Http\Request; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 单张图片 public function uploadImg(Request $request ){ if ( $request ->hasFile( 'filename' )) { $postPics = $request ->file( 'filename' ); foreach ( $postPics as $k => $v ) { $extension = $v ->extension(); $rule = [ 'jpg' , 'png' , 'gif' , 'jpeg' ]; if (!in_array( $extension , $rule )) { return '图片格式需要为jpg,png,gif格式' ; } $dir = date ( 'ymd' ); $fileName = time() . mt_rand(1, 999) . ".jpg" ; $storeResult = $v ->storeAs( 'filename' , $dir . "/" . $fileName , 'upload' ); // 默认保存位置是要到filesystem.php设置,保存到storage/app/.. $outPut [] = [ 'img_url' => "images/" . $storeResult , 'uid' => $uid , 'exam_id' => $examId , 'question_id' => $questionId , ]; } DB::table( 'x2_upload_img' )->insert( $outPut ); echo "写到数据库了,图片上去了只是ide加载很慢" ; } else { exit ( '未获得到上传文件,或上传失败' ); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// 多图上传 public function uploadImgs(Request $request ){ if ( $request ->hasFile( 'filename' )){ $postPics = $request ->file( 'filename' ); foreach ( $postPics as $k => $v ){ $extension = $v ->extension(); $rule = [ 'jpg' , 'png' , 'gif' , 'jpeg' ]; if (!in_array( $extension , $rule )){ return '图片格式需要为jpg,png,gif格式' ; } $storeResult = $v ->storeAs( 'filename' , '201810/test1.jpg' , 'upload' ); // 默认保存位置是要到filesystem.php设置,保存到storage/app/.. $outPut [] = [ 'extension' => $extension , 'store_result' => $storeResult ]; } echo "<pre>" ; print_r( $outPut ); die ; } exit ( '未获得到上传文件,或上传失败' ); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
// 上传图片第二种方式(form表单直接传过来) public uploadImg(){ $image = $_FILES [ "photo" ][ "tmp_name" ]; $fp = fopen ( $image , "r" ); $file = fread ( $fp , $_FILES [ "photo" ][ "size" ]); //二进制数据流 //保存地址 $imgDir = './Uploads/' ; //要生成的图片名字 $filename = date ( "Ym" ). "/" .md5(time().mt_rand(10, 99)). ".png" ; //新图片名称 $newFilePath = $imgDir . $filename ; $data = $file ; $newFile = fopen ( $newFilePath , "w" ); //打开文件准备写入 fwrite( $newFile , $data ); //写入二进制流到文件 fclose( $newFile ); //关闭文件 } |
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/wt1286331074/article/details/83546109