针对于YII2.0官方手册来说,我稍微修改了一些内容具体的就是把model层里定义的uoload方法在controller方法里合并了
创建模型
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model{
public $imageFile;//定义一个公用的名称
public function rules() {
return [ [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'], ];//extensions 这边报错的话就把这个设置关闭(删除后缀代码就好了)
}
}
渲染文件输入
接下来,在视图里创建一个文件输入控件
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
视图和模型的连接
现在,在控制器方法里编写连接模型和视图的代码以实现文件上传。
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
//需要自己手动创建uploads文件夹 创建在web访问目录下就ok了
class SiteController extends Controller{
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->upload()$model->validata()) {//这点就是改变的所在
$model->file->saveAs('uploads/'.$model->file->baseName.'.'.$model->file->extension);
// 文件上传成功
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
恭喜你已经学会YII2.0中的上传了
扩展::《多文件上传》
如果你想一次上传多个文件,只需调节几个参数就可以达到目的
Model:
class UploadForm extends Model
{
/**
* @var UploadedFile|Null file attribute
*/
public $file;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file', 'maxFiles' => 10], // <--- here!
];
}
}
View:
<?php
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
<?= $form->field($model, 'file[]')->fileInput(['multiple' => true]) ?>
<button>Submit</button>
<?php ActiveForm::end(); ?>
与单文件上传不同的是下面这句
$form->field($model, 'file[]')->fileInput(['multiple' => true])
Controller:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class SiteController extends Controller
{
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstances($model, 'file');
if ($model->file && $model->validate()) {
foreach ($model->file as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
}
}
return $this->render('upload', ['model' => $model]);
}
}