Yii2 example of file upload _php using uploadedfile implemented by self

Source: Internet
Author: User

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!

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.