標籤: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 檔案上傳