Validating multiple files in array

江枫思渺然 提交于 2019-11-27 15:53:05

问题


I need to validate multiple uploaded files, making sure they are of a specific type and under 2048kb. The below doesn't appear to check all files in the array 'files' and just presumes the posted files of invalid mime type as it seems to be checking the array object and not its contents.

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);             }

}

回答1:


You can validate file array like any input array in Laravel 5.2. This feature is new in Laravel 5.2. You can do like following:

$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.. 
}



回答2:


Please try this:

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);
    }
}



回答3:


Try this way.

// 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
}


来源:https://stackoverflow.com/questions/38326282/validating-multiple-files-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!