yii2.0 檔案上傳

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   os   使用   

 

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選項。

參考檔案為:yii2\basic\vendor\yiisoft\yii2\widgets\ActiveForm.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()方法儲存檔案。

至此大功告成。

參考檔案:yii2\basic\vendor\yiisoft\yii2\web\UploadedFile.php

ps:最後Yii 2.0使用了php新版本命名空間等,控制器檔案頭部記得use下就ok了。

 

yii2.0 檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.