简体   繁体   English

带有干预软件包的laravel最大图像上传验证

[英]laravel with intervention package maximum image upload validation

So i'm using intervention package to save and also resize my image if it has to big resolution, but i get MethodNotAllowedHttpException when i tried to test with uploading big images (around 10 mb ). 因此,我使用干预软件包来保存图像并调整图像的大小(如果它具有较大的分辨率),但是当我尝试测试上传大图像(大约10 mb)时出现MethodNotAllowedHttpException。

so i do some research over here and the net, there is indeed some answer but none of them work with me, i wonder why is it happen? 所以我在这里和网上做了一些研究,确实有一些答案,但是没有一个与我合作,我想知道为什么会这样吗?

try{
    $img = Input::file('gambar');

    if(!empty($img)){

        $file_max = ini_get('upload_max_filesize');
        $file_max_str_leng = strlen($file_max);
        $file_max_meassure_unit = substr($file_max,$file_max_str_leng - 1,1);
        $file_max_meassure_unit = $file_max_meassure_unit == 'K' ? 'kb' : ($file_max_meassure_unit == 'M' ? 'mb' : ($file_max_meassure_unit == 'G' ? 'gb' : 'unidades'));
        $file_max = substr($file_max,0,$file_max_str_leng - 1);
        $file_max = intval($file_max);

        $filename = $img->getClientOriginalName();


        $size = $img->getSize();

        if ($size < $file_max){
            if($this->save_image($img,$artikel,$filename)){
                $artikel->update(array(
                    'judul' => $judul,
                    'content' => Input::get('content'),
                    'kategori' => Input::get('kategori'),
                    'status' => Input::get('status'),
                    'pilihan' => Input::get('pilihan'),
                    'gambar' => $filename
                    ));
            }else{
                return Redirect::back()->withErrors($validator)->withInput();
            }
        }else{
            return Redirect::back()->withInput()->with('errormessage','El tamaño del archivo debe ser menor que %smb.',$file_max);
        }           
    }
}catch(Exception $e){
    return Redirect::back()->withInput()->with('errormessage','The file size should be lower than %s%s.',$file_max,$file_max_meassure_unit);
}

and here is my save_image function 这是我的save_image函数

function save_image($img,$artikel,$filename){

    list($width, $height) = getimagesize($img);

    $path = public_path('images_artikel/');
    File::delete($path . $artikel->gambar);

    if($width > 1280 && $height > 720){
        if(Image::make($img->getRealPath())->resize('1280','720')->save($path . $filename))
            return true;
        else
            return Redirect::back()->withInput()->with('errormessage','Terjadi kesalahan dalam penyimpanan');
    }else{
        if(Image::make($img->getRealPath())->save($path . $filename))
            return true;
        else
            return Redirect::back()->withInput()->with('errormessage','Terjadi kesalahan dalam penyimpanan');
    }
}

i also tried to use validation rules in my models but not working... 我也尝试在模型中使用验证规则,但是不起作用...

private $file_max;

function _construct(){
    $file_max = ini_get('upload_max_filesize');
    $file_max_str_leng = strlen($file_max);
    $file_max_meassure_unit = substr($file_max,$file_max_str_leng - 1,1);
    $file_max_meassure_unit = $file_max_meassure_unit == 'K' ? 'kb' : ($file_max_meassure_unit == 'M' ? 'mb' : ($file_max_meassure_unit == 'G' ? 'gb' : 'unidades'));
    $file_max = substr($file_max,0,$file_max_str_leng - 1);
    $file_max = intval($file_max);
}

// Add your validation rules here
public static $rules = [
     'judul' => 'required|between:5,255',
     'content' => 'required',
     'gambar' => 'image|mimes:jpeg,jpg,png,bmp|max:{$file_max}'

];

here is my route 这是我的路线

Route::resource('artikels','AdminArtikelsController');

and my form 和我的表格

{{ Form::model($artikel, array('route' => array('admin.artikels.update',$artikel->id), 'method' => 'put', 'files' => true)) }}

so is there other solution? 那么还有其他解决方案吗?

I believe the best practice is to create your custom validator like so: 我相信最佳做法是像这样创建您的自定义验证器:

<?php

namespace App\Validators;


use Illuminate\Validation\Validator;

class CustomImageValidator extends Validator {

    public function validateMaxResolution($attribute, $value, $parameters)
    {
        $this->requireParameterCount(1, $parameters, 'max_resolution');

        list($width, $height) = getimagesize($value);
        $resolution = explode('x', $parameters[0]);
        $max_width = $resolution[0];
        $max_height = $resolution[1];

        return ($width <= $max_width && $height <= $max_height);
    }

    protected function replaceMaxResolution($message, $attribute, $rule, $parameters)
    {
        return str_replace(':value', implode(', ', $parameters), $message);
    }

}

Then register the validator in AppServiceProvider.php 然后在AppServiceProvider.php注册验证器

<?php

namespace App\Providers;

use App\Validators\CustomImageValidator;
use Illuminate\Support\ServiceProvider;
use Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::resolver(function($translator, $data, $rules, $messages)
        { // custom image validator ;)
            return new CustomImageValidator($translator, $data, $rules, $messages);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

In your resource/lang/en/validation.php add your default message: 在您的resource/lang/en/validation.php添加默认消息:

 'max_resolution'           => 'The :attribute image resolution is too large to resize. Max resolution is :value.',

And finally add your rule to the rules array: 最后将您的规则添加到rules数组:

'your_image_field' => 'required|mimes:png,jpg,jpeg,bmp|max:1024|max_resolution:3000x3000'

This was tested on Laravel 5.1.16 (LTS) 这在Laravel 5.1.16(LTS)上进行了测试

Make sure that the route you use it as action attribute in the form is of type post, and also that the form has files activated. 确保您在表单中将其用作操作属性的路由的类型为post,并且确保表单已激活文件。 Something like this: 像这样:

For the route: 对于路线:

Route::post('upload', array('uses' => 'UploadController@handleUpload', 'as' => 'upload'));

For the form: 对于表格:

Form::open(array('route' => 'upload', 'files' => true));

check two things: 检查两件事:

  1. In your phpinfo.php: memory_limit and upload_max_filesize 在您的phpinfo.php中: memory_limitupload_max_filesize
  2. If your image processor is GD, try: Image::configure(array('driver' => 'imagick')); 如果您的图像处理器是GD,请尝试: Image::configure(array('driver' => 'imagick'));

hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM