如何在Laravel 4中验证上传文件的数组?我已经在表单中设置它以允许多个文件,并且我已经测试了文件存在于Input :: file('files')数组中。但是如何验证每个文件?
这是我尝试过的:
$notesData = array(
'date' => Input::get('date'),
'files' => Input::file('files')
);
// Declare the rules for the form validation.
$rules = array(
'date' => 'Required|date_format:Y-m-d',
'files' => 'mimes:jpeg,bmp,png,pdf,doc'
);
// Validate the inputs.
$validator = Validator::make($notesData, $rules);
// Check if the form validates with success.
if ($validator->passes())
{
// Redirect to homepage
return Redirect::to('')->with('success', 'Validation passed!');
}
// Something went wrong.
return Redirect::to(URL::previous())->withErrors($validator)->withInput(Input::all());
我希望Validator抱怨在数据数组中传递一个文件数组,但它只是通过了验证,即使我发送的文件是mp3。当我尝试上传多个文件时,它提供了一个无关的错误,即需要日期字段(尽管日期字段是自动填充的。)
我对Laravel很新。我能做些什么才能让它发挥作用?
更新:我发现问题的一部分是我的upload_max_filesize和post_max_size,我修复了。我也尝试过动态地将文件添加到数组中:
$notesData = array(
'date' => Input::get('date')
);
$i=0;
foreach(\Input::file('files') as $file){
$notesData['file'.++$i] = $file;
}
// Declare the rules for the form validation.
$rules = array(
'date' => 'Required|date_format:Y-m-d'
);
for($j=1; $j<=$i; $j++){
$rules['file'.$j] ='mimes:jpeg,bmp,png,doc';
}
但现在我收到以下错误:
不允许序列化'Symfony \ Component \ HttpFoundation \ File \ UploadedFile'
我迷路了。知道如何解决这个问题吗?
答案 0 :(得分:10)
我认为,这基本上是您最初的解决方案。对于任何仍然困惑的人,这里有一些对我有用的代码......
// Handle upload(s) with input name "files[]" (array) or "files" (single file upload)
if (Input::hasFile('files')) {
$all_uploads = Input::file('files');
// Make sure it really is an array
if (!is_array($all_uploads)) {
$all_uploads = array($all_uploads);
}
$error_messages = array();
// Loop through all uploaded files
foreach ($all_uploads as $upload) {
// Ignore array member if it's not an UploadedFile object, just to be extra safe
if (!is_a($upload, 'Symfony\Component\HttpFoundation\File\UploadedFile')) {
continue;
}
$validator = Validator::make(
array('file' => $upload),
array('file' => 'required|mimes:jpeg,png|image|max:1000')
);
if ($validator->passes()) {
// Do something
} else {
// Collect error messages
$error_messages[] = 'File "' . $upload->getClientOriginalName() . '":' . $validator->messages()->first('file');
}
}
// Redirect, return JSON, whatever...
return $error_messages;
} else {
// No files have been uploaded
}
答案 1 :(得分:3)
好吧,我不确定导致错误的是什么,但在使用验证器玩了一下后,我发现我不能一次传递所有文件。相反,我创建了一个新的数组,将每个文件与键'file0','file1'等相关联。然后我将这些传递给验证器并为每个文件设置规则(使用foreach循环)。然后验证器按预期工作。尽管如此,它还不足以满足我的需求,我最终使用了非laravel解决方案。
答案 2 :(得分:1)
这可能不是您问题的直接答案,但您可以对此类型进行简单的验证检查:
$file = Input::file('files');
switch($file->getClientMimeType()){
case 'application/pdf':
// upload stuff
break;
}
答案 3 :(得分:0)
foreach(Request::file('photos') as $key => $value) {
$rules['photos.'.$key]="mimes:jpeg,jpg,png,gif|required|max:10000";
$friendly_names['photos.'.$key]="photos";
}
这在Laravel 5.2中对我有用