1

我用 Gii 从 yii2 中的数据库表生成了一个模型。这个模型继承自 ActiveRecord 。然后我从这个模型创建了一个表单。现在我想用这个表单上传一个文件。是否可以上传具有相同模型的文件(继承自 ActiveRecord)?

如果是,如何?如果没有,我该怎么办?

4

1 回答 1

0

是的,这是可能的,但使用单独的表格是更好的做法。官方文档在上传文件一文中对此进行了很好的描述

创建单独的表格:

namespace app\models;

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

class UploadForm extends Model
{
    /**
     * @var UploadedFile
     */
    public $imageFile;

    public function rules()
    {
        return [
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

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

渲染文件输入:

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

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

    <button>Submit</button>

<?php ActiveForm::end() ?>

自定义控制器以处理文件上传:

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;

class SiteController extends Controller
{
    public function actionUpload()
    {
        $model = new UploadForm();

        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]);
    }
}

本文还介绍了上传多个文件。

另请参阅此相关问题

如果您想使用它ActiveRecord并将文件路径保存为模型属性,您可以添加模型创建和保存upload()形式的方法。另一个使用表单的好例子是Advanced Template 中的SignupForm

<?php

namespace frontend\models;
use yii\base\Model;
use common\models\User;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $username;
    public $email;
    public $password;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],
            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }

        $user = new User();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        return $user->save() ? $user : null;
    }
}

如您所见,模型的验证和创建被隔离到单独的表单中,这是更好的做法,而不是直接在模型中处理它(尤其是文件上传)。但是对于简单的目的,只使用模型也是可以接受的。

于 2016-08-01T05:23:18.690 回答