Home > php教程 > php手册 > body text

Yii2 uses its own UploadedFile to implement file upload, yii2uploadedfile

WBOY
Release: 2016-07-06 14:24:46
Original
1076 people have browsed it

Yii2 uses its own UploadedFile to implement file upload, yii2uploadedfile

Let’s first take a look at how to process image uploads supported in yii2.

First we create the modelUpload.php file

<&#63;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",],
];
}
}
Copy after login

Let’s take a look at how the view layer is rendered

<&#63;php
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]); &#63;>
<&#63;= $form->field($model, "file")->fileInput() &#63;>
<button>Submit</button>
<&#63;php ActiveForm::end(); &#63;>

Copy after login

Finally 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,
]);
}
}
Copy after login

The above is the knowledge about file upload implemented by Yii2 using its own UploadedFile introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. of. I would also like to thank you all for your support of the Bangkejia website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template