Yii2實現表單上傳檔案功能

來源:互聯網
上載者:User
本文主要介紹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'],    ];  }}

再建立一個視圖檔案,內容如下

<?phpuse 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:

<?phpuse 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]);  }}

這樣就可以實現多檔案上傳了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.