thinkphp 接Ueditor 自定义上传路径(oss)

1下载好Ueditor后修改ueditor.config.js
修改serverUrl为你自己的接口路径
serverUrl: “http://wechat.bluewhale.com/Ueditor/index”

2后端Ueditor/index

<?php
namespace app\wechat\controller;
use Chichoyi\ThinkOss\Facade\Oss;//引用oss
use think\Controller;

/**
 * Ueditor
 */
class Ueditor extends Controller
{
    private $fileField; //文件域名
    private $file; //文件上传对象
    private $base64; //文件上传对象
    private $config; //配置信息
    private $oriName; //原始文件名
    private $fileName; //新文件名
    private $fullName; //完整文件名,即从当前配置目录开始的URL
    private $filePath; //完整文件名,即从当前配置目录开始的URL
    private $fileSize; //文件大小
    private $fileType; //文件类型
    private $stateInfo; //上传状态信息,
    private $stateMap = array( //上传状态映射表,国际化用户需考虑此处数据的国际化
        "SUCCESS", //上传成功标记,在UEditor中内不可改变,否则flash判断会出错
        "文件大小超出 upload_max_filesize 限制",
        "文件大小超出 MAX_FILE_SIZE 限制",
        "文件未被完整上传",
        "没有文件被上传",
        "上传文件为空",
        "ERROR_TMP_FILE" => "临时文件错误",
        "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
        "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
        "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
        "ERROR_CREATE_DIR" => "目录创建失败",
        "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
        "ERROR_FILE_MOVE" => "文件保存时出错",
        "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
        "ERROR_WRITE_CONTENT" => "写入文件内容错误",
        "ERROR_UNKNOWN" => "未知错误",
        "ERROR_DEAD_LINK" => "链接不可用",
        "ERROR_HTTP_LINK" => "链接不是http链接",
        "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确",
        "INVALID_URL" => "非法 URL",
        "INVALID_IP" => "非法 IP",
    );
    public function __construct()
    {
        date_default_timezone_set("Asia/chongqing");
        error_reporting(E_ERROR);
        header("Content-Type: text/html; charset=utf-8");
        parent::__construct();
        //解决跨域
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS');
        header('Access-Control-Allow-Headers:*');

    }

    public function index()
    {
        //接收的action方法如果是config返回配置信息如果是别的走上传
        $action = hsc($this->request->get('action'));
        if ($action == 'config') {
           //自己配置的信息需要啥上Ueditor官网查看
            $config = [
                "imageActionName" => "uploadimage", /* 执行上传图片的action名称 */
                // "imageUrl" => "http://wechat.bluewhale.com/Ueditor/index?action=uploadimage",
                "imageFieldName" => "upfile", /* 提交的图片表单名称 */
                "imageMaxSize" => 2048000, /* 上传大小限制,单位B */
                "imageAllowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
                "imageCompressEnable" => true, /* 是否压缩图片,默认是true */
                "imageCompressBorder" => 1600, /* 图片压缩最长边限制 */
                "imageInsertAlign" => "none", /* 插入的图片浮动方式 */
                "imageUrlPrefix" => '', /* 图片访问路径前缀 */
                "imagePathFormat" => "/images/uploads/{yyyy}{mm}{dd}/{time}{rand:6}",
            ];
            //返回json格式
            $result = json_encode($config);
            // $config = json_decode($config);
            // return json_encode($config, JSON_PARTIAL_OUTPUT_ON_ERROR);
            // $rrr = json_decode($config);
            // echo $rrr;die;
            // $arr = file_get_contents("http://wechat.bluewhale.com/php/config.json");
            // $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", $arr), true);
            // $callback = $this->request->get('callback');
            // $CONFIG['callback'] = $callback;
            // echo 123;
            // return Content(callback+"("+返回的Json+")");
            /* 输出结果 */
            //如果请求地址带callback参数 需要给人返回去要不有跨域问题
            //重点被坑了一下午
            if (isset($_GET["callback"])) {
                if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                    echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
                } else {
                    echo json_encode(array(
                        'state' => 'callback参数不合法',
                    ));
                }
            } else {
                echo $result;
            }
            // echo json_encode($CONFIG);
            // die();
        } else {
            $file = $this->file = $_FILES['upfile'];
            if (!$file) {
                $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            }
            if ($this->file['error']) {
                $this->stateInfo = $this->getStateInfo($file['error']);
            } else if (!file_exists($file['tmp_name'])) {
                $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            } else if (!is_uploaded_file($file['tmp_name'])) {
                $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            }

            $this->oriName = $file['name'];
            $this->fileSize = $file['size'];
            $this->fileType = $this->getFileExt();
            $this->fullName = $this->getFullName();
            $this->filePath = $this->getFilePath();
            $this->fileName = $this->getFileName();
            $dirname = dirname($this->filePath);
            //检查文件大小是否超出限制

            // if (!$this->checkSize()) {
            //     $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            //     return;
            // }

            //检查是否不允许的文件格式
            // if (!$this->checkType()) {
            //     $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            //     return;
            // }

            //创建目录失败
            if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
                $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            } else if (!is_writeable($dirname)) {
                $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            }
            //移动文件到本地
            //移动文件
            if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
                $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
            } else { //移动成功 
                //走自己的上传方法



                $this->stateInfo = $this->stateMap[0];
                $info = Oss::localToOss($this->filePath);
                unlink($this->filePath);
                if (array_key_exists('path', $info)) {
                    $url = '/' . $info['path'];
                } else {
                    $url = '';
                }
                $ret = array(
                    "state" => $this->stateInfo,
                    "url" => CDNDomain() . $url,//加上自己的oss域名前缀
                    "title" => $this->fileName,
                    "original" => $this->oriName,
                    "type" => $this->fileType,
                    "size" => $this->fileSize,
                );
                return json_encode($ret);


            }

        }

    }
    /**
     * 上传错误检查
     * @param $errCode
     * @return string
     */
    private function getStateInfo($errCode)
    {
        return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
    }
    /**
     * 获取文件扩展名
     * @return string
     */
    private function getFileExt()
    {
        return strtolower(strrchr($this->oriName, '.'));
    }

    /**
     * 重命名文件
     * @return string
     */
    private function getFullName()
    {
        //替换日期事件
        $t = time();
        $d = explode('-', date("Y-y-m-d-H-i-s"));
        $format = $this->config["pathFormat"];
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);

        //过滤文件名的非法自负,并替换文件名
        $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
        $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
        $format = str_replace("{filename}", $oriName, $format);

        //替换随机字符串
        $randNum = rand(1, 10000000000) . rand(1, 10000000000);
        if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
            $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
        }

        $ext = $this->getFileExt();
        return time() . rand(1000, 9999) . $ext;
    }

    /**
     * 获取文件名
     * @return string
     */
    private function getFileName()
    {
        return substr($this->filePath, strrpos($this->filePath, '/') + 1);
    }

    /**
     * 获取文件完整路径
     * @return string
     */
    private function getFilePath()
    {

        $fullname = $this->fullName;
        $rootPath = $_SERVER['DOCUMENT_ROOT'];
        if (substr($fullname, 0, 1) != '/') {
            $fullname = '/' . $fullname;
        }

        return $rootPath . $fullname;
    }

    /**
     * 文件类型检测
     * @return bool
     */
    private function checkType()
    {
        return in_array($this->getFileExt(), $this->config["allowFiles"]);
    }

    // /**
    //  * 文件大小检测
    //  * @return bool
    //  */
    // private function checkSize()
    // {
    //     return $this->fileSize <= ($this->config["maxSize"]);
    // }
}

公众号技术谈论
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ThinkPHP5是一款基于PHP的开源框架,它提供了许多方便的功能来简化开发过程。其中,paginate是ThinkPHP5框架自带的一个用于分页的方法。 paginate方法用于在查询结果中进行分页,以便在网页上展示数据。使用paginate方法,可以非常方便地实现数据的分页显示,并且框架会自动处理分页链的生成和点击。 在使用paginate方法时,我们可以根据自己的需求进行自定义,以便满足特定的分页需求。具体的自定义方法如下: 首先,我们需要在模型文件中添加paginate方法的自定义配置。在模型文件中找到paginate方法,可以看到其实际上调用了系统的paginate方法。我们可以在模型文件中添加自定义配置,如: ```php public function paginate($listRows = 15, $simple = false, $config = []) { // 自定义分页配置 $config['query'] = request()->param(); $config['type'] = 'app\common\paginator\Bootstrap'; return parent::paginate($listRows, $simple, $config); } ``` 在上述代码中,我们可以看到对paginate方法进行了扩展,添加了$query和$type配置项。其中,$query用于保留当前页面的查询条件,而$type用于指定分页类的命名空间。我们可以根据自己的需求进行相应的配置。 下来,在视图文件中生成分页链时,我们可以通过自定义模板来实现样式的自定义ThinkPHP5框架提供了内置的Bootstrap模板,在生成分页链时可以指定使用该模板。具体的代码如下: ```php $paginate->render('app\common\paginator\Bootstrap'); ``` 在上述代码中,我们可以看到通过render方法指定了使用的分页模板。我们可以根据自己的需求指定其他模板,并进行样式的自定义。 综上所述,通过自定义paginate方法的配置和分页模板的选择,我们可以对ThinkPHP5框架中的paginate进行自定义,以便满足特定的分页需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值