用yii2进行文件上传功能实现

2021-11-24 15:10:52 浏览数 (1)

在common/models/下的Upload.php文件.

代码语言:javascript复制
<?php

namespace commonmodels;

use Yii;

/**
 * This is the model class for table "upload".
 *
 * @property string $file
 */
class Upload extends yiidbActiveRecord
{
    public $file;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'upload';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png,jpg,txt,jpeg,php,json,XLS,doc', 'checkExtensionByMimeType' => false]
        ];
    }

    /**
     * @inheritdoc
     */


   public function upload()
    {
        if ($this->validate()) {

           // $res = $this->file->saveAs(mkdir("C:/Wnmp/html/demonstration/frontend/uploads/" . mkdir(date('Ymd/His')."/",0777, true).$this->file->baseName . '.' . $this->file->extension));
            return $tt = $this->file->baseName . '.' . $this->file->extension;


        } else {
            echo exit();
        }
    }

}
代码语言:javascript复制
UploadController.php
<?php
namespace frontendcontrollers;
use commonmodelsUpload;
use yiihelpersArrayHelper;
use yiihelpersFileHelper;
use yiiwebUploadedFile;
class UploadController extends Controller
{

    public  function actionUpload()
    {
        $request = Yii::$app->request;
        $model = new Upload();
        $model->file = UploadedFile::getInstance($model, 'file');

        $res = $model->upload();
        echo $res;
        }
  }

postman:

0 人点赞