使用验证器设置图像最大文件大小

esi*_*iaz 2 upload image yii2

我正在使用File Input Widget在Yii2中实现图像上传,如http://demos.krajee.com/widget-details/fileinput所示.我可以知道如何设置上传的文件大小限制吗?

我已经添加了:

['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1024],
Run Code Online (Sandbox Code Playgroud)

在模型内部,rules()但它似乎不起作用.

希望有人可以提供建议.谢谢.

在视图中:

<?php $form = ActiveForm::begin(['enableClientValidation' => false,  'options' => [ 'enctype' => 'multipart/form-data']]); ?>


<?php

echo $form->field($model, 'image')->widget(FileInput::classname(), [
    'options'=>['accept'=>'image/*', 'multiple'=>true],
    'pluginOptions'=>['allowedFileExtensions'=>['jpg', 'jpeg', 'gif','png']]
]);

?>

<?php ActiveForm::end(); ?>
Run Code Online (Sandbox Code Playgroud)

在控制器中:

    $model = new IMAGEMODEL();  

    Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/PROJECT/';


    if ($model->load(Yii::$app->request->post())) {
        // get the uploaded file instance. for multiple file uploads
        // the following data will return an array
        $image = UploadedFile::getInstance($model, 'image');


        // store the source file name
        $model->FILENAME = $image->name;
        $ext = end((explode(".", $image->name)));

        // generate a unique file name

        $model->AVATAR = Yii::$app->security->generateRandomString().".{$ext}";
        $model->STD_ID=$_POST['IMAGEMODEL']['STD_ID'];


        // the path to save file, you can set an uploadPath
        // in Yii::$app->params (as used in example below)
        $path = Yii::$app->params['uploadPath'] . $model->AVATAR;

        if($model->save()){
            $image->saveAs($path);
            Yii::$app->session->setFlash('success', 'Image uploaded successfully');
            return $this->redirect(['view', 'id'=>$id]);

        } else {
            Yii::$app->session->setFlash('error', 'Fail to save image');
        }
    }
Run Code Online (Sandbox Code Playgroud)

在模型中:

public function rules()
{
    return [
        [['STD_ID', 'FILENAME'], 'required'],
        [['FILENAME'], 'string'],
        [['LAST_UPD_ON'], 'safe'],
        [['STD_ID'], 'string', 'max' => 50],
        [['LAST_UPDATE_BY'], 'string', 'max' => 150],

        [['image', 'FILENAME'], 'safe'],
        ['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1],

    ];
}
Run Code Online (Sandbox Code Playgroud)

aro*_*hev 7

1) maxSize参数需要字节数.在您的示例中,您设置1 Gb.2 Mb应该是:

['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 2],
Run Code Online (Sandbox Code Playgroud)

2)同时检查upload_max_filesizeINI设置.

3)确保在验证之前通过调用getInstance()方法(对于多个文件使用getInstances())传递yii\web\UploadedFile的实例:

$this->image = UploadedFile::getInstance($this, 'image');
Run Code Online (Sandbox Code Playgroud)