yii2.0 文件上传

Yii 2.0 出来好长时间了,一直都是看下官方网站,没实践过,今天弄了下图片上传操作。

1创建一个简单的数据表

mysql> desc article;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| title   | varchar(60)  | NO   | MUL | NULL    |                |
| image   | varchar(100) | NO   |     | NULL    |                |
| content | text         | NO   |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

数据表结构很简单:自增ID,文章标题,文章缩略图,文章内容。

2使用Gii生成一个文章表的Model,再生成一个CURD.

gii确实是很好用的工具,简单快速,具体教程可参考下面链接地址。

地址:http://www.yiichina.com/guide/2/start-gii

3 修改模板文件

修改_form.php(添加和修改模板文件公用)

<div class="article-form">

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

    <?= $form->field($model, 'title')->textInput(['maxlength' => 60]) ?>
    <?= $form->field($model, 'image')->fileInput() ?>
    <?= $form->field($model, 'content')->textarea(['rows' => 6]) ?>

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

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

</div>

上面代码中,需要注意的就是ActiveForm::begin()方法里面制定的options选项。

参考文件为:yii2asicvendoryiisoftyii2widgetsActiveForm.php,打开看下就明白,指定的选项也就是该类下的静态属性。

4 修改控制器方法

    $model = new Article();
        $rootPath = "uploads/";
        if (isset($_POST['Article'])) {
            $model->attributes = $_POST['Article'];
            $image = UploadedFile::getInstance($model, 'image');
            $ext = $image->getExtension();
            $randName = time() . rand(1000, 9999) . "." . $ext;
            $path = abs(crc32($randName) % 500);
            $rootPath = $rootPath . $path . "/";
            if (!file_exists($path)) {
                mkdir($rootPath,true);
            }
            $image->saveAs($rootPath . $randName);
            $model->image = $rootPath.$randName;

            if ($model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

该action中,首先调用UploadedFile::getInstance(),返回一个实例化对象。

通过getExtension()获取文件后缀名,然后随机生成一个文件名,即$randName。

然后为了多目录存储,使用了crc32函数。

最后直接调用saveAs()方法保存文件。

至此大功告成。

参考文件:yii2asicvendoryiisoftyii2webUploadedFile.php

ps:最后Yii 2.0使用了php新版本命名空间等,控制器文件头部记得use下就ok了。

原文地址:https://www.cnblogs.com/kongxs/p/4143321.html