使用 Laravel 4 验证多个文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18079240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:14:08  来源:igfitidea点击:

Validating multiple file uploads with Laravel 4

phplaravel

提问by Chris

How do I go about validating an array of uploaded files in Laravel 4? I've set it in the form to allow multiple files, and I've tested that the files exist in the Input::file('files') array. But how do I validate each file?

我如何在 Laravel 4 中验证一系列上传的文件?我在表单中将其设置为允许多个文件,并且我已经测试过这些文件是否存在于 Input::file('files') 数组中。但是我如何验证每个文件?

Here's what I've tried:

这是我尝试过的:

$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());

I expected Validator to complain about passing an array of files inside the data array, but it just passed validation even though the file I sent it was an mp3. When I tried to upload multiple files, it gave an unrelated error that the date field is required (though the date field was autopopulated).

我希望 Validator 抱怨在数据数组中传递文件数组,但它只是通过了验证,即使我发送的文件是 mp3。当我尝试上传多个文件时,它给出了一个不相关的错误,即日期字段是必需的(尽管日期字段是自动填充的)。

I'm pretty new to Laravel. What could I do to get this working?

我对 Laravel 很陌生。我该怎么做才能让它发挥作用?

UPDATE: I figured out part of the problem was my upload_max_filesize and post_max_size, which I fixed. I've also tried dynamically adding the files to the arrays as so:

更新:我发现问题的一部分是我的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'; 
    }

But now I'm getting the following error:

但现在我收到以下错误:

Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

不允许序列化 'Symfony\Component\HttpFoundation\File\UploadedFile'

And I'm lost. Any idea how to fix this?

我迷路了。知道如何解决这个问题吗?

采纳答案by Chris

Well, I'm not exactly sure what was causing the error, but after playing around a bit with the validator, I figured out that I couldn't just pass all the files at once. Instead, I made a new array that associated each file with keys 'file0', 'file1', etc. Then I passed these to the validator and set rules for each one (using a foreach loop). Then the validator worked as expected. Still, it wasn't flexible enough for my needs and I ended up using a non-laravel solution.

好吧,我不确定是什么导致了错误,但是在使用验证器玩了一会儿之后,我发现我不能一次传递所有文件。相反,我创建了一个新数组,将每个文件与键“file0”、“file1”等相关联。然后我将它们传递给验证器并为每个文件设置规则(使用 foreach 循环)。然后验证器按预期工作。尽管如此,它还是不够灵活,无法满足我的需求,我最终使用了非 Laravel 解决方案。

回答by Nick

I think, this is basically your initial solution. For anybody who's still confused, here's some code that worked for me…

我认为,这基本上是您的初始解决方案。对于仍然感到困惑的任何人,这里有一些对我有用的代码......

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

回答by Robert ten Wolde

It might not be the direct answer for your question, but you can do a simple validation check on types like this:

它可能不是您问题的直接答案,但您可以对这样的类型进行简单的验证检查:

$file = Input::file('files');

switch($file->getClientMimeType()){
      case 'application/pdf':
           // upload stuff
      break;
}

回答by Stephen Ainsworth

foreach(Request::file('photos') as $key => $value) {
    $rules['photos.'.$key]="mimes:jpeg,jpg,png,gif|required|max:10000";
    $friendly_names['photos.'.$key]="photos";
}

This worked for me in Laravel 5.2

这在 Laravel 5.2 中对我有用