在根目录下夹uploads文件夹
控制器 UploadController.php
<?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();
// 判断是否是POST表单提交
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model,'file');
// var_export($model->file);die;
if($model->file->saveAs(\yii::$app->basePath.'/../uploads/'.$model->file->baseName.'.'. $model->file->extension)){
$this->redirect(['site/index']);
}else{
echo"上传失败";
}
} else {
return $this->render('upload', ['model' => $model]);
}
}
}
model层UploadForm.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']) ?>