如何在yii2框架中验证除image之外的文件

时间:2016-07-12 08:12:38

标签: php yii2 yii2-advanced-app yii2-basic-app

我想上传带有yii2框架的apk文件。

在模型中

public function rules()
{
    return [
        [['apkFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'apk','mimeTypes'=>'application/*'],
    ];
}

public function upload()
{
    if ($this->validate()) {
        $this->apkFile->saveAs('affiliate/apkuploads/' . $this->apkFile->baseName . '.' . $this->apkFile->extension);
        return true;
    } else {
        return false;
    }
}

在控制器中

public function actionCreate()
{
    $model = new ManageLinks();
    $post = Yii::$app->request->post();

    if(!empty($post)){
        $model->apkFile = UploadedFile::getInstance($model, 'apkFile');

        if ($model->upload()) {
            echo 'True';
        }else{
            echo 'False';
        }
    }
    return;
    return $this->render('create', [
        'model' => $model,
        'data' => $data,
    ]);

}

格式

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'apkFile')->fileInput() ?>


<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

执行此操作后,我得到了错误的回复。请帮我解决一下这个。 在我的localhost中,我在affiliate文件夹下托管yii2框架。我的完整网址是:

http://localhost/affiliate/web/index.php

1 个答案:

答案 0 :(得分:-1)

['enctype' => 'multipart/form-data']

以你的形式开始,即

<?= Html::beginForm(['order/update', 'id' => $id], 'post', ['enctype' => 'multipart/form-data']) ?>
  

http://www.yiiframework.com/doc-2.0/guide-helper-html.html#creating-forms