2015-06-27 137 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。 –