普通网友 2014-07-24 17:12
浏览 300
已采纳

Laravel图像和图像大小验证

Dear StackOverflow community

I'm having a hard time figuring out why my image-validation doesn't work as it's supposed to. I am validating on the fact that the form::file() should be an image, as well as 400x300 px in size. For this, I am using the module image validator from cviebrock (https://github.com/cviebrock/image-validator). It think it worked before I reinstalled my OS, but I am not sure because it could be that I might have accidently removed or modified some good code.

I am 99% positive that I am validating on the \Input:file('name'), because I did a var dump on the validation attribute which should hold the file. You can see this var dump below (var_dump from $input['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

My validator class, and a 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."
    ];
}

Before the input is handled in my UserRepository class, I reorder the Input with a static fetchinput method. I am aware that this is not 100% clean code, but I am still a student so I'm still learning:

<?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;
    }
} 

When I post the form, I get a response which shows a validation error because the file isn't an image and is not 400x300 px in size.

I have been searching the web and stackoverflow for hours so I am realy desperate for this to work. If the issue lies not in my code: I have added the module from cviebrock to my composer.json and updated it trough my terminal.

{
    "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"
}

Thanks for your time.

Ps: sorry if my english is bad.

Ps *: I thought that it might be useful for you guys to add the code of my PostRepository class too. The method make( $input (which is \Input::all() ) is called by my PostController and returns a response there.

<?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. ** : Here is a var dump of the validator object

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条回答 默认 最新

  • doulan6245 2014-07-24 23:16
    关注

    I found the error, so I'm posting it should there be someone that is in need of this. Apperantly, you must validate the image BEFORE moving it to a folder. When you move the image, the temporary folder no longer holds the image.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器