2015-06-27 142 views
3

我試圖一次上傳多個圖像。文件正在上傳,但即使它們不是有效的圖像,它們也會通過驗證。我想上傳所有有效的文件,並返回帶有werent上傳成功的文件數量的消息。Laravel 5上傳多個圖像驗證

我的功能:

public function addImages($id, Request$request) 
{ 
    $files = Input::file('images'); 
    $uploaded = 0; 
    $failed = 0; 
    foreach ($files as $file) { 

     // Validate each file 
     $rules = array('file' => 'required|image'); 
     $validator = Validator::make(array('file'=> $file), $rules); 

     if($validator->passes()) { 
      $destinationPath = 'uploads'; 
      $filename = $file->getClientOriginalName(); 
      $upload_success = $file->move($destinationPath, $filename); 
      if($upload_success){ 
       $uploaded ++; 
      } 
      else { 
       $failed ++; 
      } 
     } else { 
      $failed ++; 
     } 
    } 
    \Session::flash('success_message',$uploaded.' files uploaded.'); 
    if($failed > 0){ 
     \Session::flash('errors','Some files werent valid.'); 
    } 
    return redirect('admin/myroute/'.$id); 
} 

對於如果我上傳withhout他們仍然上傳過任何擴展名的文件的一些原因。我究竟做錯了什麼?

回答

2

您不應該在控制器中驗證它,您應該使用每種方法,例如在您的請求文件中。

protected function getValidatorInstance() 
{ 
    $validator = parent::getValidatorInstance(); 


    $validator->each('files', ['image']); 

    return $validator; 
} 

這只是檢查所有的文件。

更多信息,

Laravel API about validation

-1

如果你服用你應該指定喜歡的文件類型,你可以指定名稱,並驗證這樣的「形象」驗證=>「默劇:JPEG,JPG ,bmp,png'。希望這會有所幫助

+0

圖像已經與mime一起使用,不需要這樣做。 –

+0

圖像是輸入字段名稱,MIME是驗證 –

+1

圖像也是一個驗證規則,它默認使用mimes:jpeg,jpg,png,bmp。 –