laravel文件上传

来源:互联网 发布:无线音响 知乎 编辑:程序博客网 时间:2024/05/17 09:46

上传文件配置config/filesystems.php

'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',                    // 文件将上传到storage/app/uploads目录                   'root' => storage_path('app/uploads'),                    // 文件将上传到public/uploads目录 如果需要浏览器直接访问请设置                    // 'root' => public_path('uploads'),                ],**        's3' => [            'driver' => 's3',            'key' => env('AWS_KEY'),            'secret' => env('AWS_SECRET'),            'region' => env('AWS_REGION'),            'bucket' => env('AWS_BUCKET'),        ],    ],

ImgController.php

<?phpnamespace App\Http\Controllers;use App\Http\Controllers\Controller;use DB;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Facades\Input;class ImgController extends Controller{    public function index(){        return view('img/index');    }    public function add(){        $post=Input::all();        $file=$post['image'];        if ($file->isValid()) {            $originalName = $file->getClientOriginalName(); // 文件原名            $ext = $file->getClientOriginalExtension();     // 扩展名            $realPath = $file->getRealPath();   //临时文件的绝对路径            $type = $file->getClientMimeType();     // image/jpeg            // 上传文件            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;            // 使用我们新建的uploads本地存储空间(目录)            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));            // var_dump($bool);            $url='http://'.$_SERVER['HTTP_HOST'].dirname(dirname($_SERVER['SCRIPT_NAME'])).'/storage/app/uploads/'.$filename;                if($bool){                $data=array(                    'img'=>$url,                    'addtime'=>time()                );                $res=DB::table('img')->insert($data);                if($res){                    echo '<script>alert("添加成功");location.href="'.'show'.'";</script>';                }            }        }    }    public function show(){        $data=DB::table('img')->get();        return view('img/show',['data'=>$data]);    }}

视图 img.php

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>add</title></head><body><center><form action="add" method="post" enctype="multipart/form-data">    <input type="file" name="image">    <input type="submit" value="upload"></form></center></body></html>
原创粉丝点击