YII2.0上傳文件

針對於YII2.0官方手冊來講,我稍微修改了一些內容具體的就是把model層裏定義的uoload方法在controller方法裏合併了php

建立模型

namespace app\models;web

use yii\base\Model;app

use yii\web\UploadedFile;yii

class UploadForm extends Model{this

 public $imageFile;//定義一個公用的名稱spa

  public function rules() {code

    return [ [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'], ];//extensions 這邊報錯的話就把這個設置關閉(刪除後綴代碼就行了)orm

  }ip

 

}get

 

渲染文件輸入

 

接下來,在視圖裏建立一個文件輸入控件

<?php
use yii\widgets\ActiveForm; ?>

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

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


<?php ActiveForm::end() ?>

視圖和模型的鏈接

如今,在控制器方法裏編寫鏈接模型和視圖的代碼以實現文件上傳。

namespace app\controllers;
//須要本身手動建立uploads文件夾  建立在web訪問目錄下就ok了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()$model->validata()) {//這點就是改變的所在
        $model->file->saveAs('uploads/'.$model->file->baseName.'.'.$model->file->extension); // 文件上傳成功 return; } } return $this->render('upload', ['model' => $model]); } }

                      恭喜你已經學會YII2.0中的上傳了

擴展::《多文件上傳》
 

若是你想一次上傳多個文件,只需調節幾個參數就能夠達到目的

 

Model:

 
class UploadForm extends Model { /** * @var UploadedFile|Null file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [['file'], 'file', 'maxFiles' => 10], // <--- here! ]; } } 
 

View:

 
<?php use yii\widgets\ActiveForm; $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <?= $form->field($model, 'file[]')->fileInput(['multiple' => true]) ?> <button>Submit</button> <?php ActiveForm::end(); ?> 
 

與單文件上傳不一樣的是下面這句

 
$form->field($model, 'file[]')->fileInput(['multiple' => true]) 
 

Controller:

 
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->file = UploadedFile::getInstances($model, 'file'); if ($model->file && $model->validate()) { foreach ($model->file as $file) { $file->saveAs('uploads/' . $file->baseName . '.' . $file->extension); } } } return $this->render('upload', ['model' => $model]); } }
相關文章
相關標籤/搜索