我們先來看看在yii2中支持的圖片上傳怎么進行處理的。
首先我們創(chuàng)建model\Upload.php文件
<?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",],
];
}
}
下面我們看看view層是怎么渲染的
<?php
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]); ?>
<?= $form->field($model, "file")->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end(); ?>
最后實現(xiàn)controller層的實現(xiàn)
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,
]);
}
}
以上所述是小編給大家介紹的Yii2使用自帶的UploadedFile實現(xiàn)的文件上傳的相關(guān)知識,希望對大家有所幫助