2017-03-06 207 views
0

我想驗證使用laravel驗證上傳的文件,但我有問題。Laravel圖像上傳驗證

這裏是我的代碼:

$this->validate($request, [ 
     'image' =>'mimetypes:image/jpeg,image/png,image/gif', 

     ]); 

     $avatar = $request->file('image'); 

     $fileName = time(). '.' . $avatar->getClientOriginalExtension(); 
     Image::make($avatar)->resize(300,300)->save(public_path('uploads/avatar/' . $fileName)); 

     $user = Auth::user(); 
     $user->avatar = $fileName; 
     $user->save(); 

的問題是,當我使用一個bmp文件,我得到這個錯誤: Gd error

我使用的干預形象包裝。我寧願不轉向想象力的司機。

任何想法?

+0

我想你必須在圖像陣列中聲明BMP啞劇。像這樣:'image'=>'mimetypes:image/jpeg,image/png,image/gif,image/bmp', –

+0

你正在使用哪種干涉圖像包版本? –

回答

0

望着干預封裝代碼,你可以看到兩種實現的processBmp功能:

干預/圖片/ GD/Encoder.php:

protected function processBmp() 
{ 
    throw new \Intervention\Image\Exception\NotSupportedException(
     "BMP format is not supported by Gd Driver." 
    ); 
} 

干預/圖片/ Imagick/Encoder.php:

protected function processBmp() 
{ 
    $format = 'bmp'; 
    $compression = \Imagick::COMPRESSION_UNDEFINED; 
    $imagick = $this->image->getCore(); 
    $imagick->setFormat($format); 
    $imagick->setImageFormat($format); 
    $imagick->setCompression($compression); 
    $imagick->setImageCompression($compression); 
    return $imagick->getImagesBlob(); 
} 

所以我認爲這是肯定地說,你不能用GD司機做到這一點,只能用imagick。

0

只需使用"intervention/image": "~2"或將您的驅動程序更改爲Imagick。 GD本身不支持BMP是已知的問題。您可以查看issue page on github瞭解詳情。

0

爲什麼你不使用Laravel自定義規則的圖像image

$this->validate($request, [ 
     'image' =>'image', 

     ]); 
0

希望這個解決方案將解決您的錯誤,請嘗試下面的邏輯

public function postUpload(Request $request) 
    { 

    $input = $request->all(); 
    $rules = array(
     'uploadFile' => 'image|max:8000' 
    ); 

    $validation = Validator::make($input, $rules); 

    if ($validation->fails()) 
    { 
     return array(
      'validation_failed' => true, 
      'errors'   => $validation->errors()->toArray() 
    ); 
    } 

    $file = $request->uploadFile; 
    $destinationPath = 'uploads/img'; 

    // Get real extension according to mime type 
    $ext = $file->extension(); 
    // Hash processed file name, including the real extension 
     $hashname   = date('H.i.s').'-'.md5($request->_token).'.'.$ext; 
     $upload_success  = $request->uploadFile->storeAs($destinationPath, $hashname); 


     Image::configure(array('driver' => 'imagick')); 
     $img = Image::make(storage_path() . '/app/uploads/img/' . $hashname); 
     $img->resize(230, null, function ($constraint) { 
       $constraint->aspectRatio(); 
     }); 
     $img->save(storage_path() . '/app/uploads/lowres/' .$hashname ,80); 

     $user_image = new User_images(); 
     $user_image->id_user = Auth::user()->id; 
     $user_image->handler = $hashname; 
     $user_image->save(); 


     return array('status' => 'success','message'=> 'Image has been uploaded successfully','file_path'=>'/uploads/'.$hashname);