代码之家  ›  专栏  ›  技术社区  ›  HugeD

Yii2在将文件上载到服务器时返回错误。为什么?

  •  0
  • HugeD  · 技术社区  · 7 年前

    我的观点:

    <?php
        $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
    ?>
    
    <?= $form->field($model, 'document_file')->fileInput()->label(Yii::t('app', 'Attachment')) ?>
    
    <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-primary']) ?>
    <?php ActiveForm::end(); ?>
    

    我的型号:

    class Documents extends \yii\db\ActiveRecord
    {
    
        public $document_file;
    
        public function rules()
        {
            return [
                [['document_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, xls'],
            ];
        }
    
    }
    

    我的控制器:

    $model = new Documents();
    if($model->load(Yii::$app->request->post()) && $model->validate()) {
        $model->document_file = UploadedFile::getInstance($model, 'document_file');
        $model->document_file->saveAs('uploads/documents/' . $model->document_file->baseName . '.' . $model->document_file->extension);
    } else {
        print_r($model->getErrors());
    }
    return $this->render('new', compact('model'));
    

    此代码应该将文件上载到服务器。但我从print\r中得到错误-它说

    数组([文档\u文件]=>数组([0]=>上载文件。))

    我做错了什么?如何将文件上载到服务器???

    1 回复  |  直到 7 年前
        1
  •  0
  •   drodata    7 年前

    文件属性( document_file 在您的示例中)无法通过 load() ,因此以下表达式的值为 false :

    $model->load(Yii::$app->request->post()) && $model->validate()
    

    这就是您收到打印错误消息的原因。您应该使用 UploadedFile::getInstance() 分配 document\u文件 属性 之前 validate() :

    $model = new Documents();
    if(Yii::$app->request->isPost) {
        $model->document_file = UploadedFile::getInstance($model, 'document_file');
        if ($model->validate()) {
            $model->document_file->saveAs('uploads/documents/' . $model->document_file->baseName . '.' . $model->document_file->extension);
        } else {
            print_r($model->getErrors());
        }
    }
    return $this->render('new', compact('model'));