2016-07-12 2 views
5

여러 업로드 파일의 유효성을 검사해야합니다. 파일이 특정 유형이고 2048kb 미만인지 확인해야합니다. 아래는 배열 의 'files'에있는 모든 파일을 검사하는 것으로 보이지 않으며 잘못된 mime 유형의 게시 된 파일은 배열 객체를 검사하는 것으로 보이고 내용은 검사하지 않습니다.배열의 여러 파일 유효성 확인

public function fileUpload(Request $request) 
    { 

     $validator = Validator::make($request->all(), [ 
      'files' => 'required|mimes:jpeg,jpg,png', 
     ]); 

     if ($validator->fails()) 
     { 
      return response()->json(array(
       'success' => false, 
       'errors' => $validator->getMessageBag()->toArray() 

      ), 400);    } 

} 

답변

15

당신은 Laravel 5.2의 모든 입력 배열과 같은 파일 배열의 유효성을 검사 할 수 있습니다. 이 기능은 Laravel 5.2에서 새로 추가되었습니다. 다음과 같이 할 수 있습니다.

$input_data = $request->all(); 

$validator = Validator::make(
    $input_data, [ 
    'image_file.*' => 'required|mimes:jpg,jpeg,png,bmp|max:20000' 
    ],[ 
     'image_file.*.required' => 'Please upload an image', 
     'image_file.*.mimes' => 'Only jpeg,png and bmp images are allowed', 
     'image_file.*.max' => 'Sorry! Maximum allowed size for an image is 20MB', 
    ] 
); 

if ($validator->fails()) { 
    // Validation error.. 
} 
+0

감사합니다. 배열의 모든 파일이 5MB를 초과 할 수없는 규칙을 만드는 약식 방법이 있는지 궁금합니다. – LaserBeak

+0

최대 값을 'max : 5000'으로 변경하십시오. –

+0

하지만 이미지 파일 당 또는 전체 배열에 대해 5000KB가됩니까? 파일 당 추측합니다. – LaserBeak

3

이 시도하십시오

public function fileUpload(Request $request) { 
    $rules = []; 
    $files = count($this->input('files')) - 1; 
    foreach(range(0, $files) as $index) { 
     $rules['files.' . $index] = 'required|mimes:png,jpeg,jpg,gif|max:2048'; 
    } 

    $validator = Validator::make($request->all() , $rules); 

    if ($validator->fails()) { 
     return response()->json(array(
      'success' => false, 
      'errors' => $validator->getMessageBag()->toArray() 
     ) , 400); 
    } 
} 
0

이 방법을 사용해보십시오.

// getting all of the post data 
$files = Input::file('images'); 

// Making counting of uploaded images 
$file_count = count($files); 

// start count how many uploaded 
$uploadcount = 0; 

foreach($files as $file) { 
    $rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc' 
    $validator = Validator::make(array('file'=> $file), $rules); 
     if($validator->passes()){ 
      $destinationPath = 'uploads'; 
       $filename = $file->getClientOriginalName(); 
       $upload_success = $file->move($destinationPath, $filename); 
       $uploadcount ++; 
     } 
} 

if($uploadcount == $file_count){ 
    //uploaded successfully 
} 
else { 
    //error occurred 
}