【问题标题】:Yii2 max_size validation issueYii2 max_size 验证问题
【发布时间】:2017-07-14 11:30:59
【问题描述】:

这是我的行动:

public function actionCustom() {
    $model = new Custom();

    $model->load(\Yii::$app->request->post());

    if ($model->validate()) {
        // emptying the model's data
        $model = new Custom();

        var_dump('good');
    } else {
        var_dump('bad');
    }

    var_dump($_FILES);

    return $this->render('custom', [
        'model' => $model
    ]);
}

这是我的模型:

class Custom extends Model
{
    public $file;

    public function rules()
    {
        return [
//            ['file', 'file', 'extensions' => ['png', 'jpg', 'jpeg', 'gif', 'txt'], 'maxSize' => 1024 * 100]
            ['file', 'file', 'maxSize' => 1024 * 100],
        ];
    }
}

当我尝试上传大小超过我设置的 maxSize 规则的文件时,客户端验证显示错误,我无法通过单击按钮提交表单,这很好,但我可以强制通过在控制台中输入类似这样的内容来提交,就像黑客会做的那样:

document.forms[0].submit()

我得到这个输出:

C:\wamp64\www3\controllers\SiteController.php:138:string 'good' (length=4)

C:\wamp64\www3\controllers\SiteController.php:143:
array (size=1)
  'Custom' => 
    array (size=5)
      'name' => 
        array (size=1)
          'file' => string 'tste.txt' (length=8)
      'type' => 
        array (size=1)
          'file' => string 'text/plain' (length=10)
      'tmp_name' => 
        array (size=1)
          'file' => string 'C:\wamp64\tmp\phpDE60.tmp' (length=25)
      'error' => 
        array (size=1)
          'file' => int 0
      'size' => 
        array (size=1)
          'file' => int 818064

string 'good' 表示文件通过了验证,但是怎么样?!我发送的文件大小为 818064,大于我设置的 102400 (1024 * 100) 文件大小限制。

我做错了什么?

【问题讨论】:

  • php.ini 中的 upload_max_filesize 和 post_max_size 是什么?

标签: validation yii2


【解决方案1】:

您是否尝试过使用官方文档示例中提到的yii\web\UploadedFile::getInstance() 方法?

$model = new UploadForm();

if (Yii::$app->request->isPost) {
    $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
    if ($model->upload()) {
        // file is uploaded successfully
        return;
    }
}

http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html#wiring-up

【讨论】:

  • 不,我没有。你的意思是我应该在验证之前尝试将UploadedFile::getInstance($model, 'file') 设置为“文件”属性?
  • @Razip 是的,试试吧。
  • @Razip 如果您不手动设置文件属性,您的验证规则将被忽略(您可以使用skipOnEmpty = false 强制执行此操作)
  • @csminb,你能告诉它如何执行吗?
  • ['file', 'file', 'maxSize' => 1024 * 100, 'skipOnEmpty' => false ],
猜你喜欢
  • 2015-07-16
  • 2018-03-12
  • 2015-05-22
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多