Laravel框架--文件上传

新的工作开始了,新项目是基于laravel框架开发的,在此将我认为使用较多的功能整理成博客以供参阅。

我是用的框架版本是 5.2.45

先来看配置文件 根目录\config\filesystems.php
在这里我们可以设置将文件上传到哪,比如我在此上传到我的项目中,并且上传到storage\app\uploads目录下,则需要如下设置。详情请看我代码中的注释!!

'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'visibility' => 'public',
        ],
      ///////////////////////下面是我加的代码/////////////////////////
      //这里的uploads 就是我控制器代码中  Storage::disk('uploads')的 ‘uploads’ 
      //表明我用的是这个设置
        'uploads' => [
            'driver' => 'local',
            'root' => storage_path('app/uploads'),
        ],
        /*********如果想要放到其他目录下
        'uploads' => [
            //上传到本地
            'driver' => 'local',
            //如下设置 则上传到public目录下的uploads 文件夹
            'root' => public_path('uploads'),
        ],
        ********/
        ///////////////////////上面是我加的代码/////////////////////////
        's3' => [
            'driver' => 's3',
            'key' => 'your-key',
            'secret' => 'your-secret',
            'region' => 'your-region',
            'bucket' => 'your-bucket',
        ],

    ],

首先前端demo代码贴出来如下:

<form method="post" action="" enctype="multipart/form-data">
    {{ csrf_field() }}
    请选择文件<input type="file" value="" name="file" >
    <br>
    <button type="submit">提交</button>
</form>

后端代码为:

<?php
namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller{
    public function file(Request $request){
        if($request->isMethod('post')){
            //获取前端上传的文件  name="file"
            $file = $request->file('file');
//            var_dump($file);exit;
            //判断文件是否上传成功
            if($file->isValid()){
                //原文件名称
                $name = $file->getClientOriginalName();
                //扩展名
                $extension = $file->getClientOriginalExtension();
                //文件类型
                $type = $file->getClientMimeType();
                //临时文件的绝对路径
                $realPath = $file->getRealPath();

                //命名
                $fileName = date('Y-m-d-H-i-s').uniqid().'.'.$extension;
                //上传到指定目录  这个地方为啥是uploads  请看我配置代码中的解释
                $bool = Storage::disk('uploads')->put($fileName,file_get_contents($realPath));
                //打印出来为 true 则上传成功
                var_dump($bool);
            }
        }
        return view('file');
    }
}

当上传成功了之后,去对应的文件夹下就能看到上传的文件了。

猜你喜欢

转载自blog.csdn.net/qq_32737755/article/details/80775431
今日推荐