Yii2 Yii 2文件验证程序

Yii2 Yii 2文件验证程序,yii2,yii2-validation,Yii2,Yii2 Validation,我是Yii 2的新手,阅读文档并进行实验。使用ActiveForm并尝试进行文件上载时,我不断收到一个错误“请上载文件”,即使在我逐步执行代码时,文件似乎已上载 模型代码 public function upload() { if ($this->validate()) { $destination = Yii::getAlias('@app/uploads'); $this->brochure->saveAs($destina

我是Yii 2的新手,阅读文档并进行实验。使用
ActiveForm
并尝试进行文件上载时,我不断收到一个错误“请上载文件”,即使在我逐步执行代码时,文件似乎已上载

模型代码

public function upload()
{
    if ($this->validate())
    {
        $destination = Yii::getAlias('@app/uploads');

        $this->brochure->saveAs($destination . '/' . $this->product_id . '.' . $this->brochure->extension);
        return true;
    }
    else
    {
        return false;
    }
}
控制器代码

public function actionUpdate($id)
{
    $model = $this->findModel($id);

    if (Yii::$app->request->isPost)
    {
        $model->load(Yii::$app->request->post());
        $upload = UploadedFile::getInstance($model, 'brochure');

        if ($upload !== null)
        {
            $model->brochure = $upload;
            $result = $model->upload();
        }

        // If model is saved, update product_to_language db table for language checkboxes
        if ($model->save())
        {
            // First delete all old values in product_to_language db table
            $cmd = Yii::$app->db->createCommand()
                ->delete('product_to_language', "product_id = $model->product_id")
            ;
            $result = $cmd->execute();

            // Next update product_to_language db table
            $form = Yii::$app->request->post('Product');

            if (!empty($languages = $form['languages']))
            {
                // Create array of values for batch insert
                foreach ($languages as $language_id)
                {
                    $insert_array[] = [$model->product_id, $language_id];
                }

                $cmd = Yii::$app->db->createCommand()
                    ->batchInsert('product_to_language',
                        ['product_id', 'language_id'],
                        $insert_array
                    )
                ;
                $result = $cmd->execute();
            }

            return $this->redirect(['view', 'id' => $model->product_id]);
        }
    }

    return $this->render('update', [
        'model' => $model,
    ]);
}
_表格代码

<?php
use app\models\Product;
use app\models\Brand;
use app\models\Language;
use app\models\Color;
use app\models\Gender;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Product */
/* @var $form yii\widgets\ActiveForm */
?>


<div class="admin-product-form">

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

<?php
    $errors = $form->errorSummary($model);
    echo $errors;
?>

<?= $form->field($model, 'product_name')->textInput() ?>

<?= $form->field($model, 'brand_id')->label('Brand')->dropDownList(Brand::getOptions(), ['prompt' => 'Select Brand']) ?>

<?= $form->field($model, 'price')->textInput() ?>

<?php $model->isNewRecord ? $model->color_id = 1 : $model->color_id = $model->color_id ; ?>
<?= $form->field($model, 'color_id')->dropDownList(Color::getOptions()) ?>

<?= $form->field($model, 'gender_id')->radioList(Gender::getOptions(), ['prompt' => 'Select Gender']) ?>

<?= $form->field($model, 'languages')->checkboxList(Language::getOptions()) ?>

<?= $form->field($model, 'description')->textarea(['rows' => 6, 'class' => 'tinymce', 'maxlength' => true]) ?>

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

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

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

</div>

链接到屏幕截图
您的模型应该为
brouchure
制定正确的规则,如下所示:

public function rules()
{
    return [
        [
            'brouchure',
            'file',
            'extensions' => ['png', 'jpg', 'jpeg', 'svg'],
            'maxSize' => 1024 * 1024
        ]
        ...
    ];
}

注意:如果在
load
之后获得
null
属性值,则应检查
规则
。属性对于加载应该是安全的。

您的模型应该为
brouchure
设置正确的规则,如下所示:

public function rules()
{
    return [
        [
            'brouchure',
            'file',
            'extensions' => ['png', 'jpg', 'jpeg', 'svg'],
            'maxSize' => 1024 * 1024
        ]
        ...
    ];
}

注意:如果在
load
之后获得
null
属性值,则应检查
规则
。属性应该可以安全加载。

另外,不要忘记上传目录的写入权限

确保您的web服务器可以写入@app/uploads目录

在我的例子中,在调用saveAs之前,我检查存在什么上传目录,并设置写入权限

$file_name = $model->$brochure->baseName. '.' . $model->$brochure->extension;
$path = Yii::getAlias('@app/uploads');
$full_path = $path . $file_name;

if(!is_dir($path)){                //  check path exist
     @mkdir($path, 0755, true);    //  if not, create dir and set permission
}

touch($path.'/index.htm');         // create empty index.html 
                                   // for reduce risk scan dir outside 

$model->$brochure->saveAs($full_path);
在您的示例中,这段代码将是多余的,因为您可以手动检查写入权限。
但对于动态文件夹创建,这是一种良好的做法,例如,对于个人用户文件夹

另外,不要忘记上传目录的写入权限

确保您的web服务器可以写入@app/uploads目录

在我的例子中,在调用saveAs之前,我检查存在什么上传目录,并设置写入权限

$file_name = $model->$brochure->baseName. '.' . $model->$brochure->extension;
$path = Yii::getAlias('@app/uploads');
$full_path = $path . $file_name;

if(!is_dir($path)){                //  check path exist
     @mkdir($path, 0755, true);    //  if not, create dir and set permission
}

touch($path.'/index.htm');         // create empty index.html 
                                   // for reduce risk scan dir outside 

$model->$brochure->saveAs($full_path);
在您的示例中,这段代码将是多余的,因为您可以手动检查写入权限。
但对于动态文件夹创建,这是一种良好的做法,例如,对于个人用户文件夹

请添加您的代码。您可以添加您的模型、控制器和表单代码吗。另外,您获得的当前输出的屏幕截图?请添加您的代码。您可以添加您的模型、控制器和表单代码吗。还有当前输出的屏幕截图?检查rules()函数是正确的。我已将maxFiles设置为2,这是导致问题的原因。您检查rules()函数是正确的。我已将maxFiles设置为2,这是导致问题的原因。