1.创建 模型如下:
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016/7/26
* Time: 20:14
*/
namespace app\modules\forum\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
public $file;
public function rules(){
return [
[['file'],'file'],//可以将验证规则写的更加具体
];
}
}
2.视图:
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016/7/26
* Time: 20:17
*/
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]);
?>
<?= $form->field($model,'file')->fileInput()?>
<button>Submit</button>
<?php ActiveForm::end();?>
3.控制器
3.1.单图片(文件)上传控制器代码:
public function actionUpload(){
//echo Yii::$app->basePath;exit();
$model = new UploadForm();
if(Yii::$app->request->isPost){
$model->file = UploadedFile::getInstance($model,'file');//获取上传文件实例
if($model->validate()){
$model->file->saveAs(Yii::$app->basePath.'/modules/uploads/'.$model->file->baseName.'.'.$model->file->extension);
}
}
return $this->render('upload',['model'=>$model]);
}
3.2.多图片(文件)上传控制器代码:
public function actionUploads(){
$model = new UploadForm();
if(Yii::$app->request->isPost){
$files = UploadedFile::getInstances($model,'file');
foreach($files as $file){
$_model = new UploadForm();
$_model->file = $file;
if($_model->validate()){
$_model->file->saveAs(Yii::$app->basePath.'/modules/uploads/'.$_model->file->baseName.'.'.$_model->file->extension);
}else {
foreach($_model->getErrors('file') as $error){
$model->addError('file',$error);
}
}
}
if($model->hasErrors('file')){
$model->addError(
'file',
count($model->getErrors('file')).'of'.'files not uploaded'
);
}
}
return $this->renderPartial('uploads',['model'=>$model]);
}
注意在使用前,先要引入UploadFile类:
use yii\web\UploadedFile;
好了,现在就可以实现你的图片(文件)上传了!