yii2利用自带UploadedFile实现上传图片的示例
程序员文章站
2024-03-13 19:49:57
本人搜索了很多关于yii2利用自带uploadedfile实现上传图片介绍,下面我来记录一下。
创建一个 models/uploadform.php:
name...
本人搜索了很多关于yii2利用自带uploadedfile实现上传图片介绍,下面我来记录一下。
创建一个 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() ?>
控制器
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]); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。