这时我轻轻地闭上了眼睛,我好像来到童话世界,好像在和小鸟讨论秋天的美景,好像在和小草拍秋天的照片。农民伯伯在田野里收获了庄稼,果农们在果园里收获了果子,我们在学校里收获快乐、收获知识、收获成长。
本人搜索了很多关于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]); }
本文yii2利用自带UploadedFile实现上传图片的示例到此结束。上游,是勇士劈风破浪的终点;下游,是懦夫一帆风顺的归宿。小编再次感谢大家对我们的支持!