Yii2 uploading _php instances using the UploadedFile implemented with your own files

Source: Internet
Author: User
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!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.