這篇文章主要介紹了Yii2使用表單上傳檔案的實例程式碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧
yii2用表單上傳檔案常用到的,該怎麼上傳呢?
1、單一檔案上傳
#先建立一個模型models/UploadForm.php,內容如下
namespace app\models; use yii\base\Model; use yii\web\UploadedFile; /** * UploadForm is the model behind the upload form. */ class UploadForm extends Model { /** * @var UploadedFile file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [['file'], 'file'], ]; } }
再建立一個視圖文件,內容如下
<?php use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?> <?= $form->field($model, 'file')->fileInput() ?> <button>Submit</button> <?php ActiveForm::end() ?>
最後建立控制器文件,內容如下
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::getInstance($model, 'file'); if ($model->file && $model->validate()) { $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension); } } return $this->render('upload', ['model' => $model]); } }
注意這裡我們沒有用model->load(...),而是用了UploadedFile::getInstance(...)。差別是後者不會執行$model->validate(),所以需要手動的去執行$model->validate()來檢驗資料的合法性。如果檢驗通過了,上傳的檔案保存在uploads資料夾下,即web目錄下的uploads裡。
一些可選的設定選項
上傳檔案不能為空
public function rules() { return [ [['file'], 'file', 'skipOnEmpty' => false], ]; }
上傳類型,不僅可以根據副檔名檢驗,也可以根據文件的內容進行檢驗
public function rules() { return [ [['file'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png',], ]; }
#2、多文件上傳
##如果你想一次上傳多個文件,只要調節幾個參數就可以達到目的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]); } }這樣就可以實現多檔案上傳了。 ###
以上是Yii2利用表單進行檔案上傳的實例講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!