Yii2 UploadedFile實作檔案上傳
#在Yii裡上傳檔案通常使用yii\web\UploadedFile類,它把每個上傳的檔案封裝成 UploadedFile 物件。結合yii\widgets\ActiveForm和models,你可以輕鬆實現安全的上傳檔案機制。
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]); } }
這樣就可以實現多檔案上傳了。
更多相關知識,請造訪 PHP中文網! !
以上是yii2怎麼實現檔案上傳?的詳細內容。更多資訊請關注PHP中文網其他相關文章!