yii2框架实现文件上传
最近在开发项目中用到文件上传,特意来写一下如何利用yii2自带的小物件来实现文件上传。
正如很多人百度到的,方法全部一样。
首先控制器层:
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use frontend\models\UploadForm;
use yii\web\UploadedFile;
class FileController extends Controller
{
public $layout=false;
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost){
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if($model->upload()){
echo "上传成功";
}
}else{
return $this->render('file', ['model' => $model]);
}
}
}
模型层:
<?php
namespace frontend\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* @var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[
['imageFile'], 'file', 'extensions' => 'png, jpg'
],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
echo "验证失败";
return false;
}
}
}
其次视图层:
<?php
use yii\widgets\ActiveForm;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
</body>
</html>
下一篇将介绍如何实现多文件上传