Let's take a look at how the image uploads supported in Yii2 are handled.
First we create the model\upload.php file
<?php
namespace Backend\models;
Use Yii;
Use Yii\web\uploadedfile;
Class Upload extends \yii\db\activerecord
{
/**
* @var uploadedfile| Null file Attribute
* * public
$file;
/**
* @return array the validation rules.
* * Public
function rules ()
{return [[
[' file '], ' file ',],
];
}
}
Now let's see how the View layer is rendered.
<?php use
yii\widgets\activeform;
$form = Activeform::begin (["Options" => ["Enctype" => "Multipart/form-data"]];?> <?=
$form-> Field ($model, "file")->fileinput ()?>
<button>Submit</button>
<?php ActiveForm:: End ();?>
Finally realization of controller layer
namespace Backend\controllers;
Use Backend\models\upload;
Use Yii\web\uploadedfile;
Class Toolscontroller extends \yii\web\controller
{
/**
* File Upload
* We upload the picture after the success of the address
of the return * * * Public Function Actionupload ()
{
$model = new Upload ();
$uploadSuccessPath = "";
if (Yii:: $app->request->ispost) {
$model->file = uploadedfile::getinstance ($model, "file");
File upload stored directory
$dir = ". /.. /public/uploads/". Date (" Ymd ");
if (!is_dir ($dir))
mkdir ($dir);
if ($model->validate ()) {
//filename
$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 above is a small set to introduce the YII2 use of uploadedfile to achieve the implementation of the relevant knowledge of the file upload, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!