laravel文件上传

laravel 文件上传方法

第一步:创建本地磁盘

在 config中找到filesystems.php ,里面新增一个uploads磁盘

'disks' => [

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

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

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

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],

第二步在控制器中创建方法

public function uploads(Request $request)
    {
        if($request->isMethod('POST')){
            $files = $request->file('carid');
            // 文件是否上传成功
            if($files->isValid()){
                // 原文件名
                $originalName = $files->getClientOriginalName();
                // 扩展名
                $ext = $files->getClientOriginalExtension();
                // 文件类型
                $type = $files->getMimeType();
                // 临时文件绝对路径
                $realPath = $files->getRealPath();
				// 要保存在项目中的文件名
                $filesName = date('Y-m-d-H-i-s'). '-'.uniqid().'.'.$ext;
				// 执行保存至本地磁盘
                $bool = Storage::disk('uploads')->put($filesName,file_get_contents($realPath));
//                var_dump($bool);
                $data = [
                    'code' => $bool?0:1,
                    'msg' => '',
                    'data'=>$bool ? $filesName:'',
                ];

                return response()->json($data);
            }

            exit;
        }
        return view('student.upload');
    }

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章