yii2利用自带UploadedFile实现上传图片的示例
时间:2021-09-25 08:18:27|栏目:PHP代码|点击: 次
本人搜索了很多关于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]); }
上一篇:php URL跳转代码 减少外链
栏 目:PHP代码
下一篇:单一index.php实现PHP任意层级文件夹遍历(Zjmainstay原创)
本文标题:yii2利用自带UploadedFile实现上传图片的示例
本文地址:http://www.codeinn.net/misctech/177328.html