Yii2 implement form upload file function

Source: Internet
Author: User
Tags yii
This article mainly introduces Yii2 use form upload file instance code, small series think very good, now share to everybody, also give everybody make a reference. Follow the small series together to see it, hope to help everyone.

1. Single File Upload

First set up a model models/uploadform.php, the content is as follows

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 '], '  }}

Then create a view file with the following content

<?phpuse yii\widgets\activeform;? ><?php $form = Activeform::begin ([' options '] = [' enctype ' = ' multipart/form-data ']]? ><?= $form- >field ($model, ' file ')->fileinput ()? ><button>submit</button><?php activeform::end ()?>

Finally, the controller file is set up as follows:

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

Note that we did not use the Model->load (...), but instead used the uploadedfile::getinstance (...). The difference is that the latter does not perform $model->validate (), so it is necessary to manually execute $model->validate () to verify the legitimacy of the data. If the test passes, the uploaded file is saved in the Uploads folder, which is the uploads in the Web directory.

Some optional configuration options

The upload file cannot be empty

Public Function Rules () {  return [[[    ' file '], ' file ', ' skiponempty ' = false],  ];}

The upload type can be verified not only by extension, but also by the contents of the file.

Public Function Rules () {  return [[    ' file '], ' file ', ' extensions ' = ' jpg, png ', ' mimetypes ' = ' image/jpeg ' , Image/png ',],  ];}

2, multi-file upload

If you want to upload multiple files at once, just adjust a few parameters to achieve your goal.

Model:

Class Uploadform extends model{  /**   * @var uploadedfile| Null file Attribute   */public  $file  ; /**   * @return array the validation rules.   */Public  function rules ()  {    return [[[      ' file '], ' file ', ' maxfiles ' +],//<---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 ();?>

Unlike single-file uploads, the following sentence

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

This allows for multiple file uploads.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.