YII上传图片完整代码

Posted 想她

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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上传图片完整代码的主要内容,如果未能解决你的问题,请参考以下文章

Yii框架上传后展示图片

Yii Crop Image 上传使用 Ajax 问题

yii2.0图片上传

Yii 框架 - 使用 Rest Client 上传图片

Yii2上传图片插件使用

yii2.0上传图片