Home Backend Development PHP Tutorial Yii2 implements form upload file function

Yii2 implements form upload file function

Jan 30, 2018 pm 02:01 PM
yii2 upload document

This article mainly introduces the example code of Yii2 using forms to upload files. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

1. Single file upload

First create a model models/UploadForm.php with the following content

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'],
    ];
  }
}
Copy after login

Then create a view file with the following content

<?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() ?>
Copy after login

Finally create the controller file, the content is 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]);
  }
}
Copy after login

Note that we did not use model->load(...) here, but used UploadedFile::getInstance(...). The difference is that the latter will not execute $model->validate(), so you need to manually execute $model->validate() to check the validity of the data. If the verification passes, the uploaded file is saved in the uploads folder, that is, uploads in the web directory.

Some optional configuration options

The uploaded file cannot be empty

public function rules()
{
  return [
    [['file'], 'file', 'skipOnEmpty' => false],
  ];
}
Copy after login

The upload type can be checked not only based on the extension, but also based on the content of the file Check

public function rules()
{
  return [
    [['file'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png',],
  ];
}
Copy after login

2. Multiple file upload

If you want to upload multiple files at one time, you only need to adjust a few parameters to achieve the 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' => 10], // <--- here!
    ];
  }
}
Copy after login

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(); ?>
Copy after login

The difference from single file upload is the following sentence

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

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

This way, multiple files can be uploaded.

Related recommendations:

PHP and AjaxForm implement asynchronous file upload with progress bar

jQuery ajaxupload plug-in implementation Detailed explanation of uploading files without refreshing

Detailed explanation of Ajax form asynchronous upload file example code

The above is the detailed content of Yii2 implements form upload file function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to recover expired WeChat files? Can expired WeChat files be recovered? How to recover expired WeChat files? Can expired WeChat files be recovered? Feb 22, 2024 pm 02:46 PM

How to recover expired WeChat files? Can expired WeChat files be recovered?

Photos cannot open this file because the format is not supported or the file is corrupted Photos cannot open this file because the format is not supported or the file is corrupted Feb 22, 2024 am 09:49 AM

Photos cannot open this file because the format is not supported or the file is corrupted

Preparing for removal takes a long time in Windows 11/10 Preparing for removal takes a long time in Windows 11/10 Feb 19, 2024 pm 07:42 PM

Preparing for removal takes a long time in Windows 11/10

Can Tmp format files be deleted? Can Tmp format files be deleted? Feb 24, 2024 pm 04:33 PM

Can Tmp format files be deleted?

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk?

Upload failed, file cannot be empty, inconsistent error Upload failed, file cannot be empty, inconsistent error Feb 19, 2024 pm 01:21 PM

Upload failed, file cannot be empty, inconsistent error

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code.

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

What is hiberfil.sys file? Can hiberfil.sys be deleted?

See all articles