Laravel 5.2 pdf mime类型验证问题

时间:2016-05-27 14:58:26

标签: php laravel laravel-5.2

我无法验证pdf附件(多个),laravel 5.2。验证规则是这样的:

namespace App\Http\Requests;

class UploadRequest extends Request
{    
   public function rules()
   {   
    return [
                'attachments'=> 'required|mimes:pdf',
           ];
   }
}

namespace App\Http\Requests;

class UploadRequest extends Request
{    
   public function rules()
   {
    return [
                'attachments'=> 'required|mimetypes:application/pdf',
           ];
   }
}

我按照documentation中的建议关注。它使所有附件类型无效。

修改

当我解决这个问题时,我必须添加自定义验证方法

namespace App\Http\Requests;

use Illuminate\Validation\Factory as ValidationFactory;

class UploadRequest extends Request
{    

    public function __construct(ValidationFactory $validationFactory)
    {
       $validationFactory->extend(
           'pdf',
           function ($attribute, $files, $parameters) {

               if(is_array($files)){
                   foreach($files as $file){
                       if($file->getMimeType()!='application/pdf'){
                           return false ;
                       }
                   }
               }else
                   return $files->getMimeType()=='application/pdf';
               return true;
           },
           'File is not a pdf document'
       );


    }

    public function rules()
    {
        return [
                    'attachments'=> 'required|pdf',
               ];
    }

   }

2 个答案:

答案 0 :(得分:1)

您可以使用Intent intent = new Intent(this, CombineFragmentActivity.class);

onOptionsItemSelected字符可用于validating arrays(此处有多个附件)。

答案 1 :(得分:0)

use Validator;

class AppServiceProvider extends ServiceProvider
{
public function boot()
    {
        Validator::extend('pdf', function($attribute, $value, $parameters) {
            $allowed_mimes = [
                'application/pdf', // pdf
            ];
            return in_array($value->getMimeType(), $allowed_mimes);
        });
    }

// and in the NewsletterRequest:
public function rules()
    {
        return [
            'pdf_file' => 'pdf',
        ];
    }