Validating multiple file uploads with Laravel 4

后端 未结 4 1706
遥遥无期
遥遥无期 2021-02-06 17:22

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(

相关标签:
4条回答
  • 2021-02-06 17:36
    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

    0 讨论(0)
  • 2021-02-06 17:45

    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;
    }
    
    0 讨论(0)
  • 2021-02-06 17:46

    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
    }
    
    0 讨论(0)
  • 2021-02-06 17:55

    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.

    0 讨论(0)
提交回复
热议问题