1. 程式人生 > >laravel圖片上傳

laravel圖片上傳

html頁面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>表單</title
>
</head> <body> <form action="
{{url('file')}}" method="post" enctype="multipart/form-data"> <table border="1" align="center"> <tr> <td>暱稱</td> <td><input type="text" name="name"/></td> </tr> <tr
>
<td>選擇圖片</td> <td><input type="file" name="photo"/></td> </tr> <tr> <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>"> <td><input type="submit" value="提交"
/>
</td> <td></td> </tr> </table> </form> </body> </html>

php接值

 $file = Request::file('photo');
        $name = Request::input('name');
        $allowed_extensions = ["png", "jpg", "gif"];
        if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
            return ['error' => 'You may only upload png, jpg or gif.'];
        }
        $destinationPath = 'storage/uploads/'; //public 資料夾下面建 storage/uploads 資料夾
        $extension = $file->getClientOriginalExtension();
        $fileName = str_random(10).'.'.$extension;
        $file->move($destinationPath, $fileName);
        $filePath = asset($destinationPath.$fileName);
       $info=DB::insert('insert into photo(pname,photo) VALUES (?,?)',[$name,$filePath]);
          if($info){
           return Redirect('/show');
          }else{
              echo "no";
          }

完畢