Laravel图像和图像大小验证

时间:2014-07-24 17:12:59

标签: php validation laravel

亲爱的StackOverflow社区

我很难弄清楚为什么我的图像验证不能正常工作。我正在验证form :: file()应该是一个图像,以及400x300像素的大小。为此,我使用了来自cviebrock(https://github.com/cviebrock/image-validator)的模块图像验证器。它认为在重新安装我的操作系统之前它有效,但我不确定,因为我可能会意外地删除或修改了一些好的代码。

我99%肯定我在\ Input:file('name')上验证,因为我在验证属性上执行了var转储,该转储应该保存文件。您可以在下面看到这个var转储(来自$ input ['fotofile']的var_dump):

object(Symfony\Component\HttpFoundation\File\UploadedFile)[9]
  private 'test' => boolean false
  private 'originalName' => string '400x300real.gif' (length=15)
  private 'mimeType' => string 'image/gif' (length=9)
  private 'size' => int 1558
  private 'error' => int 0

我的验证器类和basevalidator:

<?php

namespace validation;

class NewPostValidator extends BaseModelValidator {
    protected $rules = [
        "title" => "required|min:10",
        "beschrijving" => "required|between:175,1000" ,
        "foto"         => "required",
        "fotofile"     => "image|image-size:400,300",
        "thumbnailfile"=> "image|image-size:200,150"
    ];
    protected $messages = [
        "title.required" => "U heeft geen titel opgegeven.",
        "title.min"      => "Een titel moet bestaan uit minimum 10 tekens.",
        "beschrijving.required" => "U heeft geen beschrijving opgegeven.",
        "beschrijving.between"  => "Een beschrijving moet uit minimaal 175 en maximaal 1000 tekens bestaan.",
        "foto.required"         => "U heeft geen foto gekozen.",
        "fotofile.image"        => "Uw foto is geen afbeelding.",
        "fotofile.image-size"   => "Uw foto moet 400x300 pixels zijn.",
        "thumbnailfile.image"   => "Het thumbnailveld bevat geen afbeelding.",
        "thumbnailfile.image-size" => "Uw thumbnail moet 200x150 pixels zijn."
    ];
}

在我的UserRepository类中处理输入之前,我使用静态fetchinput方法重新排序Input。我知道这不是100%干净的代码,但我还是学生,所以我还在学习:

<?php

namespace InputFetcher;

use InputFetcher\InputFetcher;

class PostFetcher implements InputFetcher {

    public static function fetchInput( $input ){
    if(!$input['update']){
        $input['id'] = null;
    }
    $post = \Post::where('id', '=', $input['id'])->get();
        $now = new \DateTime("now");


        if(null !== \Input::file('foto')){
            $foto = \Input::file('foto');
            $input['foto'] = "/images/" . $now->format('Y-m-d') . $foto->getClientOriginalName() ;

            $input['fotofile'] = $foto;
        } else if($input['update']) {

            $input['foto'] = $post[0]->foto;
        }
        if(null !== \Input::file('thumbnail')){
            $thumb = \Input::file('thumbnail');
            $input['thumbnail'] = "/images/" . $now->format('Y-m-d') . $thumb->getClientOriginalName();
            $input['thumbnailfile'] = $thumb;

        } else if($input['update']) {

            $input['thumbnail'] = $post[0]->thumbnail;
        }
        $input['userid'] = \Auth::user()->id;

        return $input;
    }
} 

当我发布表单时,我收到一个显示验证错误的响应,因为该文件不是图像,大小不是400x300像素。

我一直在搜索网络和stackoverflow几个小时,所以我真的非常渴望这个工作。如果问题不在我的代码中:我已经将模块从cviebrock添加到我的composer.json并通过我的终端更新了它。

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "laravel/framework": "4.2.*",
        "cviebrock/image-validator": "1.0.*"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php",
            "app/classes/"

        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "stable"
}

感谢您的时间。

Ps:抱歉,如果我的英语不好。

Ps *:我认为你们也可以添加我的PostRepository类的代码。方法make($ input(它是\ Input :: all())由我的PostController调用并在那里返回一个响应。

<?php

namespace Repository;
use InputFetcher\PostFetcher;
use Exceptions\ValidationException;
use validation\NewPostValidator;
class PostRepository extends BaseRepository {

    protected $validators = [
        'newpost' => 'NewPostValidator'
    ];

    public function __construct( \Post $postModel ){
        $this->model = $postModel;
    }

    public function make ( $input ){

        $this->validator = \App::make( $this->getValidator( 'newpost' ) );
        $input['update'] = false;
        $input = PostFetcher::fetchInput( $input );
        $foto = \Input::file('foto');
        $thumb = \Input::file('thumbnail');
        $now = new \DateTime('now');
        if( null!==$foto ){
            $foto->move('images', $now->format('Y-m-d') . $foto->getClientOriginalName());
        }
        if( null!==$thumb ){
            $thumb->move('images', $now->format('Y-m-d') . $thumb->getClientOriginalName());
        }

        $result = parent::make($input);

        if( null!==$this->messageBag ){
            throw new ValidationException( implode( "&", $this->messageBag ) );
        }

        return $result; 
    }

    public function update ( $id, $input ){

        $this->validator = \App::make( $this->getValidator( 'newpost' ) );
        $input['id'] = $id;
        $input['update'] = true;
        $input = PostFetcher::fetchInput( $input );

        $foto = \Input::file('foto');
        $thumb = \Input::file('thumbnail');
        $now = new \DateTime('now');

        if( null!==$foto ){
            $foto->move('images', $now->format('Y-m-d') . $foto->getClientOriginalName());
        }
        if( null!==$thumb ){
            $thumb->move('images', $now->format('Y-m-d') . $thumb->getClientOriginalName());
        }

        $result = parent::update( $id, $input );

        if( null!==$this->messageBag ){
            throw new ValidationException( implode( "&", $this->messageBag ) );
        }

        return $result; 
    }

    public function findAll(){
        $posts = \DB::table('posts')
        ->leftJoin('user', function( $join ){
            $join->on( 'posts.userid', '=', 'user.id' );
        })
        ->orderby( 'created_at', 'desc' )->paginate('5', array( 'posts.id', 'posts.article', 'posts.beschrijving', 
                'posts.title', 'user.naam', 'user.voornaam',
                'posts.foto', 'posts.thumbnail', 'posts.created_at',
                'posts.challenge' ) );
        return $posts;
    }

    public function find( $id ){
        $post = parent::find( $id );
        $author = \DB::table( 'user' )->join('posts', 'user.id', '=', 'posts.userid')
                  ->where('posts.id', '=', $id)->get( array('naam', 'voornaam') );
        return array( 'post' => $post , 'author' => $author );                
    }

    public function postOverview(){
        return \DB::table('posts')->get();
    }

}

P.S。 **:这是验证器对象的var转储

object(validation\NewPostValidator)[242]
  protected 'rules' => 
    array (size=5)
      'title' => string 'required|min:10' (length=15)
      'beschrijving' => string 'required|between:175,1000' (length=25)
      'foto' => string 'required' (length=8)
      'fotofile' => string 'image|image-size:400,300' (length=24)
      'thumbnailfile' => string 'image|image-size:200,150' (length=24)
  protected 'messages' => 
    array (size=9)
      'title.required' => string 'U heeft geen titel opgegeven.' (length=29)
      'title.min' => string 'Een titel moet bestaan uit minimum 10 tekens.' (length=45)
      'beschrijving.required' => string 'U heeft geen beschrijving opgegeven.' (length=36)
      'beschrijving.between' => string 'Een beschrijving moet uit minimaal 175 en maximaal 1000 tekens bestaan.' (length=71)
      'foto.required' => string 'U heeft geen foto gekozen.' (length=26)
      'fotofile.image' => string 'Uw foto is geen afbeelding.' (length=27)
      'fotofile.image-size' => string 'Uw foto moet 400x300 pixels zijn.' (length=33)
      'thumbnailfile.image' => string 'Het thumbnailveld bevat geen afbeelding.' (length=40)
      'thumbnailfile.image-size' => string 'Uw thumbnail moet 200x150 pixels zijn.' (length=38)
  protected 'attributes' => 
    array (size=10)
      '_token' => string 'Jsh9xKnbAi7NUJhGA0b7l8J0yJvnerL85i9Peeh1' (length=40)
      'title' => string '' (length=0)
      'beschrijving' => string '' (length=0)
      'article' => string '' (length=0)
      'thumbnail' => null
      'foto' => string '/images/2014-07-25400x300real.gif' (length=33)
      'update' => boolean false
      'id' => null
      'fotofile' => 
        object(Symfony\Component\HttpFoundation\File\UploadedFile)[9]
          private 'test' => boolean false
          private 'originalName' => string '400x300real.gif' (length=15)
          private 'mimeType' => string 'image/gif' (length=9)
          private 'size' => int 1558
          private 'error' => int 0
      'userid' => string '24' (length=2)
  protected 'validator' => null

1 个答案:

答案 0 :(得分:2)

我发现了错误,所以如果有人需要这个,我就发帖了。显然,您必须在将图像移动到文件夹之前对其进行验证。移动图像时,临时文件夹不再保留图像。

相关问题