本文实例讲述了Laravel框架文件上传功能实现方法。分享给大家供大家参考,具体如下:
- 以Laravel 5.2.45 框架为主,进行文件上传功能的实现如下:
实现步骤:
(1). 配置文件修改
打开 config/filesystems.php 文件
在 ‘disks' 数组中添加如下代码
1
2
3
4
5
6
|
//自定义 'uploads' => [ 'driver' => 'local' , //'root' => storage_path('app/uploads'), 'root' => public_path( 'uploads/' . date ( 'Ymd' )), ], |
(2).前端视图 upload.blade.php
根据需求,设计简单的视图,核心代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
< div class = "panel panel-default" > < div class = "panel-heading" >文件上传</ div > < div class = "panel-body" > < form class = "form-horizontal" role = "form" method = "POST" action = "" enctype = "multipart/form-data" > {{ csrf_field() }} < div class = "form-group" > < label for = "file" class = "col-md-4 control-label" >Hello world</ label > < div class = "col-md-6" > < input id = "file" type = "file" class = "form-control" name = "source" > </ div > </ div > < div class = "form-group" > < div class = "col-md-6 col-md-offset-4" > < button type = "submit" class = "btn btn-primary" > < i class = "fa fa-btn fa-sign-in" ></ i > 上传 </ button > </ div > </ div > </ form > </ div > </ div > |
(3). 控制器核心代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; //上传文件 功能实现方法 public function upload(Request $request ){ if ( $request ->isMethod( 'POST' )){ $file = $request ->file( 'source' ); //判断文件是否上传成功 if ( $file ->isValid()){ //原文件名 $originalName = $file ->getClientOriginalName(); //扩展名 $ext = $file ->getClientOriginalExtension(); //MimeType $type = $file ->getClientMimeType(); //临时绝对路径 $realPath = $file ->getRealPath(); $filename = uniqid(). '.' . $ext ; $bool = Storage::disk( 'uploads' )->put( $filename , file_get_contents ( $realPath )); //判断是否上传成功 if ( $bool ){ echo 'success' ; } else { echo 'fail' ; } } } return view( 'upload' ); } |
(4). 执行上述方法结果
通过调用上述方法,正确执行后,上传的文件将出现在 public/uploads 的对应日期目录下
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/u011415782/article/details/78830129