laravel 文件上传

配置laravel 文件存储


在/config/filesystems.php 进行配置找到 'disks' => [] 这个数组,在里面新建一个配置

 'uploads'=>[
            'driver' => 'local',
            'root' => public_path('uploads/'.date("Ym")),
  ],


文件上传操作

    public function uploads(Request $request)
    {
        $file = $request->file('file');
        //判断文件是否上传成功
        if ($file->isValid()) {
            //扩展名
            $ext = $file->getClientOriginalExtension();
            //临时绝对路径
            $realPath = $file->getRealPath();
            $filename = uniqid() . '.' . $ext;
            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
            //判断是否上传成功
            if ($bool) {
                return ["code" => 0, "msg" => "上传成功", "data" => "/uploads/" . date("Ym/") . $filename];
            } else {
                return 'fail';
            }
        } else {
            return 'fail';
        }
    }