我们先来看看在yii2中支持的图片上传怎么进行处理的。
首先我们创建modelUpload.php文件
<?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层是怎么渲染的
<?php use yiiwidgetsActiveForm; $form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]); ?> <?= $form->field($model, "file")->fileInput() ?> <button>Submit</button> <?php ActiveForm::end(); ?>
最后实现controller层的实现
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, ]); } }
以上所述是小编给大家介绍的Yii2使用自带的UploadedFile实现的文件上传的相关知识,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!