Yii2.0-单文件上传

时间:2022-10-05 08:41:13

Yii2.0-单文件上传

Yii2.0-单文件上传

error: 需打开php.ini fileinfo扩展

Yii2.0-单文件上传—>—>Yii2.0-单文件上传—>—>Yii2.0-单文件上传
Yii2.0-单文件上传

创建控制器FormController

<?php 
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use frontend\models\Uploads;
use yii\web\UploadedFile;
class FormController extends Controller{
public function actionMyfile(){
$model=new Uploads();
return $this->render('myfile',['model'=>$model]);
}
public function actionGetfile(){
$model = new Uploads();
if (Yii::$app->request->isPost) {
$model->imgFile = UploadedFile::getInstance($model, 'imgFile');
//////验证大小
$fileSize=$model->imgFile->size;
$maxSize=1024*1024*10;
$minSize=1;
if($fileSize>$minSize&&$fileSize<$maxSize){
if ($model->upload()) {
// 文件上传成功
echo '上传成功';
}
}else{
echo 'error';
}
}
}

创建模型Uploads.php

<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
class Uploads extends Model
{

public $imgFile;
//验证
public function rules(){
return [
[['imgFile'], 'file','extensions' => 'png, jpg','maxSize'=>1024*1024*10,'minSize'=>1],
];
}
//上传
public function upload(){
if ($this->validate()) {
$this->imgFile->saveAs('uploads/' . $this->imgFile->baseName . '.' . $this->imgFile->extension);
return true;
} else {
return false;
}
}
}

注意这里我们没有用model->load(…),而是用了UploadedFile::getInstance(…)。区别是后者不会执行 model>validate() model->validate()来检验数据的合法性。如果检验通过了,上传的文件保存在uploads文件夹下,即web目录下的uploads里。

上传文件不能为空

public function rules()
{

return [
[['file'], 'file', 'skipOnEmpty' => false],
];
}

创建视图/views/form/myfile.php

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
'id' => 'login-form',
'options' => ['class' => 'form-horizontal','enctype' => 'multipart/form-data'],
'action'=>'?r=form/getfile',
'method'=>'post'
]) ?>

<?= $form->field($model, 'imgFile')->fileInput() ?>

<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('上传', ['class' => 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end() ?>