首页 > PHP开发 > Yii2 > yii2自带UploadedFile上传图片实现方法
2015
07-08

yii2自带UploadedFile上传图片实现方法

先创建一个 models/UploadForm.php:

<?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() ?>

最后控制器

<?php
use app\models\UploadForm;
use yii\web\UploadedFile;

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

编程技巧