首页 > 代码库 > YII上传图片完整代码

YII上传图片完整代码

//记住哦,还需要引人模板
<?php

namespace app\controllers;

use yii\web\Controller;
use yii\web\UploadedFile;

use app\models\Upload;   
 //上传图片
    public function actionUploada ()
    {
        $model = new Upload();
        $uploadSuccessPath = "";
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, "file");
            //文件上传存放的目录
            $dir = "E:/wamp/www/yii/basic/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,
        ]);
    }

 

//这个就是app/models/upload.php
<?php
namespace app\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(); ?>

 

YII上传图片完整代码