码迷,mamicode.com
首页 > Web开发 > 详细

yii2 文件上传

时间:2016-03-12 20:00:25      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:

直接贴代码了

----------------------------------------------------------------------------------------------------------

先新建一个model文件 UploadForm.php

  内容:   

<?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‘],
];
}
}

---------------------------------------------------------------------------------------------------------------------

控制器层内容:

  

function actionIndexadv(){
$request = Yii::$app->request;
$model = new UploadForm();
if($request->isPost){
$model->file = UploadedFile::getInstance($model, ‘file‘);
if ($model->file && $model->validate()) {
$r = $model->file->saveAs(‘uploads/‘ . $model->file->baseName . ‘.‘. $model->file->extension);    //这是上传,uploads文件夹要自己手动创建
}
}else{
return $this->renderPartial(‘adv_add.html‘,[‘model‘ => $model]);
}
}

----------------------------------------------------------------------------------------------------------------------------

 

显示页面内容:

 

<?php
use yii\widgets\ActiveForm;
use yii\helpers\Url;
?>

<?php $form = ActiveForm::begin([‘options‘ => [‘enctype‘ => ‘multipart/form-data‘]]) ?>

<table class="table table-bordered table-hover definewidth m10">

 

 

<tr>
   <td class="tableleft">上传广告图</td>
   <td><?= $form->field($model, ‘file‘)->fileInput() ?></td>
</tr>

<tr>
   <td class="tableleft"></td>
   <td>
       <button type="submit" class="btn btn-primary" type="button">保存</button>
       <button type="button" class="btn btn-success" name="backid" id="backid">返回广告列表</button>
   </td>
</tr>

<?php ActiveForm::end() ?>

 

yii2 文件上传

标签:

原文地址:http://www.cnblogs.com/gyrgyr/p/5269846.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!