Let’s first take a look at how to process image uploads supported in yii2.
First we create the modelUpload.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",], ]; } }
Next we look at 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, we implement the controller layer
namespace backend\controllers; use backend\models\Upload; use yii\web\UploadedFile; class ToolsController extends \yii\web\Controller { /** * 文件上传 * 我们这里上传成功后把图片的地址进行返回 */ 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 above is what the editor introduces to you Yii2 uses the built-in UploadedFile to implement file uploading knowledge. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support of this website!
The above introduces the file upload implemented by Yii2 using its own UploadedFile, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.