Yii框架文件上传

fcy6dtqo  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(141)

我正在尝试学习如何在Yii上传一个图片文件。我正在使用这个代码

<?php
use yii\widgets\ActiveForm;
?>

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

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

    <button>Submit</button>

<?php ActiveForm::end() ?>

在ProjectFile/views/site/upload.php文件中。问题位于

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

$model给了我一个红色的下划线。我看了很多例子,都是这样写的。我需要做什么来阻止这个问题?

***编辑:***位于控制器/SiteController. php中

// function for upload
    public function actionUploadImage()
    {
        $model = new UploadImageForm();

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

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

位于models/上传图像表单. php的内部

<?php

namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

class UploadImageForm extends \yii\base\Model
{

    public $imageFile;

    // gives rules of how to upload picture
    public function rules(){
        return [
          [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    // uploads picture
    public function upload(){
        if($this->validate()){
            $this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
        }
    }

}
vnjpjtjt

vnjpjtjt1#

1.请确保模型具有名为“imageFile”的属性/字段
1.检查您的编辑器,您是否在编辑器上看到红线,然后是编辑器相关问题

cnjp1d6j

cnjp1d6j2#

同样的事情也发生在我身上,你的视图代码很好。我的也是一样,我在模型函数中使用了这些行:

$imageFile= UploadedFile::getInstances($model, 'imageFile')[0];
$imageFile->saveAs('uploads/' . $imageFile->baseName . '.' . $imageFile->extension);

以及在控制器动作中:

$model->imageFile= UploadedFile::getInstances($model, 'imageFile')[0];
ulmd4ohb

ulmd4ohb3#

在views\upload.php中,红色下划线是因为系统找不到$model。在运行时,程序会将$model连接到controller。所以红色下划线对php文件来说不是问题。

相关问题