Yii2使用自带的UploadedFile实现的文件上传

首先我们创建modelUpload.php文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace backendmodels;
use Yii;
use yiiwebUploadedFile;
class Upload extends yiidbActiveRecord
{
/**
* @var UploadedFile|Null file attribute
*/
public $file;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[["file"], "file",],
];
}
}

下面我们看看view层是怎么渲染的

1
2
3
4
5
6
<?php
use yiiwidgetsActiveForm;
$form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]); ?>
<?= $form->field($model, "file")->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end(); ?>

最后实现controller层的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
namespace backendcontrollers;
use backendmodelsUpload;
use yiiwebUploadedFile;
class ToolsController extends yiiwebController
{
/**
* 我们这里上传成功后把图片的地址进行返回
*/
public function actionUpload ()
{
$model = new Upload();
$uploadSuccessPath = "";
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, "file");
//文件上传存放的目录
$dir = "../../public/uploads/".date("Ymd");
if (!is_dir($dir))
mkdir($dir);
if ($model->validate()) {
//文件名
$fileName = date("HiiHsHis").$model->file->baseName . "." . $model->file->extension;
$dir = $dir."/". $fileName;
$model->file->saveAs($dir);
$uploadSuccessPath = "/uploads/".date("Ymd")."/".$fileName;
}
}
return $this->render("upload", [
"model" => $model,
"uploadSuccessPath" => $uploadSuccessPath,
]);
}
}
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论