LeePC
我们努力不是为了成为金字塔上的人,我们努力是为了超越自己,使得自己变的更好。
 1 //测试文件上传类
 2 
 3    public function actionCreate()
 4     {
 5         $model = new Lvyou();
 6 
 7         $upload_model = new \app\models\UploadForm();  
 8 
 9         $post = Yii::$app->request->post();
10 
11         if (Yii::$app->request->isPost) {
12             $upload_model->file = \yii\web\UploadedFile::getInstance($upload_model, 'file');
13             if ($upload_model->file && $upload_model->validate()) {
14                 $filename ='./../../uploads/' . $upload_model->file->baseName . '.' . $upload_model->file->extension;
15                 $upload_model->file->saveAs($filename);
16                 $post['Lvyou']['file'] = $filename;
17                 // $ext=$model->file->extension;//上传文件后缀名
18                 // $name=$model->file->baseName;//上传文件名        
19             }
20         }
21        // if (isset($filename)) {
22        //      $post['Lvyou']['file'] = $filename;
23        //  }else{
24        //      $post['Lvyou']['file']='他是不是没上传图片呀';
25        //  }
26 
27         if ($model->load($post) && $model->save()) {
28             return $this->redirect(['view', 'id' => $model->id]);
29         } else {
30             return $this->render('create', [
31                 'model' => $model,
32                 'upload_model'=> $upload_model,
33             ]);
34         }
35         
36     }

 

 

 1 //视图层
 2 
 3 一键生成的在index
 4 
 5     <?= GridView::widget([
 6         'dataProvider' => $dataProvider,
 7         'filterModel' => $searchModel,
 8         'columns' => [
 9             ['class' => 'yii\grid\SerialColumn'],
10 
11             'id',
12             'file'=>[
13                 'attribute'=>'file',      
14                 'format' => ['image',['width'=>'100','height'=>'80',]],
15             ],
16 
17             ['class' => 'yii\grid\ActionColumn'],
18         ],
19     ]); ?>
20 
21   在_form
22 
23  <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
24 
25 <?= $form->field($upload_model, 'file')->fileInput() ?>
26 
27 <?php ActiveForm::end(); ?>

model层 UploadForm文件

 1 <?php
 2 namespace app\models;
 3 
 4 
 5 use yii\base\Model;
 6 use yii\web\UploadedFile;
 7 
 8 /**
 9 * UploadForm is the model behind the upload form.
10 */
11 class UploadForm extends Model
12 {
13     /**
14      * @var UploadedFile file attribute
15      */
16     public $file;
17 
18     /**
19      * @return array the validation rules.
20      */
21     public function rules()
22     {
23         return [
24             [['file'], 'file'],
25         ];
26     }
27 }

 

posted on 2017-03-20 19:11  三哥~!  阅读(1081)  评论(0编辑  收藏  举报