Let's take a look at the image uploads supported in Yii2 how to handle it.
First we create the model\upload.php file
<?phpnamespace 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]]," fi Le ",],];}}
Now let's see how the View layer is rendered.
<?phpuse yii\widgets\activeform; $form = Activeform::begin (["Options" = ["Enctype" and "Multipart/form-data"] ]); ><?= $form->field ($model, "file")->fileinput ()?>Submit<?php activeform::end ();? >
Finally realize the Controller layer implementation
namespace Backend\controllers;use backend\models\upload;use Yii\web\uploadedfile;class Toolscontroller extends \yii\ web\controller{/*** File Upload * We upload a successful post here to return the address of the image */public function actionupload () {$model = new Upload (); $ Uploadsuccesspath = "", If (Yii:: $app->request->ispost) {$model->file = uploadedfile::getinstance ($model, " File ")//upload 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 part of the YII2 to introduce the use of their own uploadedfile implementation of the relevant knowledge of the file upload, I hope that we have some help, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for the support of the Scripting House website!