//测试文件上传类

    public function actionCreate()
{
$model = new Lvyou(); $upload_model = new \app\models\UploadForm(); $post = Yii::$app->request->post(); if (Yii::$app->request->isPost) {
$upload_model->file = \yii\web\UploadedFile::getInstance($upload_model, 'file');
if ($upload_model->file && $upload_model->validate()) {
$filename ='./../../uploads/' . $upload_model->file->baseName . '.' . $upload_model->file->extension;
$upload_model->file->saveAs($filename);
$post['Lvyou']['file'] = $filename;
// $ext=$model->file->extension;//上传文件后缀名
// $name=$model->file->baseName;//上传文件名
}
}
// if (isset($filename)) {
// $post['Lvyou']['file'] = $filename;
// }else{
// $post['Lvyou']['file']='他是不是没上传图片呀';
// } if ($model->load($post) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'upload_model'=> $upload_model,
]);
} }
 //视图层

 一键生成的在index

     <?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'], 'id',
'file'=>[
'attribute'=>'file',
'format' => ['image',['width'=>'100','height'=>'80',]],
], ['class' => 'yii\grid\ActionColumn'],
],
]); ?>   在_form <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?> <?= $form->field($upload_model, 'file')->fileInput() ?> <?php ActiveForm::end(); ?>

model层 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'],
];
}
}
05-20 12:22