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了。