<?php namespace frontend\controllers; use Yii; use frontend\models\UploadForm; use yii\web\UploadedFile; class UploadController extends \yii\web\Controller { public function actionUpload() { //实例化model $model = new UploadForm(); //接值 if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, ‘file‘); //验证 if ($model->file && $model->validate()) { $fileName = date("Ymd H:i:s").$model->file->baseName . "." .$model->file->extension; //图片的路径 $dir = ‘uploads‘."/". $fileName; //保存 $model->file->saveAs($dir); //$model->file->saveAs(‘uploads/‘ . $model->file->baseName . ‘.‘ . $model->file->extension); } } return $this->render(‘upload‘, [‘model‘ => $model]); } } model层uploadfrom.php
<?php namespace frontend\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‘] ]; } }
view里面upload.php
<?php use yii\widgets\ActiveForm; use yii\helpers\Html; ?> <?php $form = ActiveForm::begin([‘options‘ => [‘enctype‘ => ‘multipart/form-data‘]]) ?> <?= $form->field($model,‘file‘)->fileInput() ?> <button>提交</button> <?php ActiveForm::end() ?> <?= Html::img(‘@web/uploads/1.jpg‘, [‘alt‘ => ‘My logo‘]) ?>
时间: 2024-12-24 19:34:01