PHP wangEditor插件打包(包含公式、上传附件)完整版

注意:js,css文件引用路径需要修改

先看效果

index.html文件

<!DOCTYPE html PUBLIC "-//W3C//Dtd XHTML 1.0 Strict//EN" "http://www.w3.org/tr/xhtml1/Dtd/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js/jquery-1.12.3.min.js"></script>
<!--  新版编辑器 -->
<script type="text/javascript" src="js/editor/dist/index.js"></script>
<link href="js/editor/dist/css/style.css" rel="stylesheet">
<!--  公式插件  -->
<script type="text/javascript" src="js/editor/katex/katex.js"></script>
<script type="text/javascript" src="js/editor/pluformula/index.js"></script>
<!--   上传附件 -->
<script type="text/javascript" src="js/editor/fujiandist/index.js"></script>
 </head>
<textarea
                    style="width: 800px; height: 400px; outline: none;"
                    id="body" name="body"
                ><?= $row["body"] ?></textarea>

                <style>
                    #editor—wrapper {
                        border: 1px solid #ccc;
                        z-index: 100; /* 按需定义 */
                        width: 100%;
                    }

                    #toolbar-container {
                        border-bottom: 1px solid #ccc;
                    }

                    #editor-container {
                        height: 500px;
                    }
                </style>

                <div id="editor—wrapper">
                    <div id="editor-toolbar" style="border-bottom: 1px solid #ccc;"></div>
                    <div id="editor-text-area" style="height: 500px"></div>
                </div>
                <script>
                    const E = window.wangEditor
                    const LANG = location.href.indexOf('lang=en') > 0 ? 'en' : 'zh-CN'
                    E.i18nChangeLanguage(LANG) // 切换语言
                    //自带公式插件
                    E.Boot.registerModule(window.WangEditorPluginFormula.default)
                    //上传附件插件
                    E.Boot.registerModule(window.WangEditorPluginUploadAttachment.default)

                    //公式插件
                    class MyKityFormulaMenu {
                        constructor() {
                            this.title = '公式'
                            this.iconSvg = '<svg t="1686991680388" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1152" width="200" height="200"><path d="M552.0896 565.90336L606.03392 512l-53.94432-53.90336L290.6112 196.83328l551.0144-0.29696v-76.25728l-659.17952 0.3584v76.25728L498.14528 512 182.3744 827.50464v75.85792l659.17952 0.3584v-76.25728l-551.0144-0.29696 261.55008-261.26336" p-id="1153" fill="#595959"></path></svg>'
                            this.tag = 'button'
                            this.showModal = true;
                            this.modalWidth = 900;
                            this.modalHeight = 600;
                        }

                        isActive(editor) {//默认选中
                            return false;
                        }

                        getValue(editor) {
                            return '';
                        }

                        isDisabled(editor) {//只读设置
                            return false;
                        }

                        exec(editor, value) {

                        }

                        getModalPositionNode(editor) {
                            return null; // modal 依据选区定位
                        }

                        // 定义 DropPanel 内部的 DOM Element
                        getModalContentElem(editor) {
                            // panel 中需要用到的id
                            const inputIFrameId = "kityformula_" + Math.ceil(Math.random() * 10);
                            const btnOkId = "kityformula-btn" + Math.ceil(Math.random() * 10);

                            const $content = $(`
    <div>
      <iframe id="${inputIFrameId}" class="iframe" height="400px" width="100%" frameborder="0" scrolling="no" src="js/editor/kityformula/index.html"></iframe>
    </div>`);
                            const $button = $(
                                `<div style="display: flex;justify-content: flex-end;">
<button id="${btnOkId}" type="button" class="right" style='margin: 5px 0'>
        确认插入
      </button></div> `

                            );
                            $content.append($button);

                            $button.on("click", () => {
                                // 执行插入公式
                                const node = document.getElementById(inputIFrameId);
                                const kfe = node.contentWindow.kfe;

                                kfe.execCommand("get.image.data", function (data) {
                                    // 获取base64
                                    // console.log(data.img);
                                });

                                let latex = kfe.execCommand("get.source");
                                latex = latex.replace(/\s/g, ""); // 去掉空格
                                const formulaNode = {
                                   type: "formula",
                                    value: latex,
                                    children: [
                                        {
                                            text: "",
                                        },
                                    ],
                                };
                                editor.restoreSelection();//恢复选区
                               editor.insertNode(formulaNode);
                                editor.hidePanelOrModal;
                            });

                            return $content[0]; // 返回 DOM Element 类型

                            // PS:也可以把 $content 缓存下来,这样不用每次重复创建、重复绑定事件,优化性能
                        }
                    }

                    // 插件配置
                    const myMenuConf = {
                        key: 'kityFormula',
                        factory() {
                            return new MyKityFormulaMenu()
                        }
                    }
                    // 插件注入
                    E.Boot.registerMenu(myMenuConf)

                    //上传附件插件

                    window.editor = E.createEditor({
                        selector: '#editor-text-area',
                        html: $("#body").val(),
                        config: {
                            placeholder: '请输入内容...',
                            hoverbarKeys: {
                                formula: {
                                    menuKeys: ['editFormula'], // “编辑公式”菜单
                                },
                                attachment: {
                                    menuKeys: ['downloadAttachment'], // “下载附件”菜单
                                },
                            },
                            //配置上传信息
                            MENU_CONF: {
                                'uploadImage': {
                                    server: '../adminIsAdmin/js/editor/_up.php?act=main',
                                    timeout: 30 * 1000, // 上传时间
                                    fieldName: 'upfile', //字段名称
                                    meta: {file_type: 'image'}, //POST参数
                                    metaWithUrl: false,  // 将 meta 拼接到 url 参数中,默认 false
                                    headers: {Accept: 'text/x-json', admintoken: ''},// admintoken是否验证登录状态
                                    // 单个文件的最大体积限制,默认为 10M
                                    maxFileSize: 10 * 1024 * 1024,
                                    maxNumberOfFiles: 10,//最多可上传几个文件
                                    allowedFileTypes: ['image/*'],// 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
                                    //小于该值就插入 base64 格式(而不上传),默认为 0
                                    // base64LimitSize: 5 * 1024,
                                    // 上传之前触发
                                    onBeforeUpload(file) {
                                        return file
                                    },
                                    // 上传进度的回调函数
                                    onProgress(progress) {
                                    },
                                    // 单个文件上传成功之后
                                    onSuccess(file, res) {
                                    },
                                    // 单个文件上传失败
                                    onFailed(file, res) {
                                        alert(res.message)
                                    },
                                    // 上传错误,或者触发 timeout 超时
                                    onError(file, err, res) {
                                        alert(err.message)
                                    },
                                },
                                'uploadVideo': {
                                    server: '../adminIsAdmin/js/editor/_up.php?act=main',
                                    timeout: 30 * 1000, // 上传时间
                                    fieldName: 'upfile', //字段名称
                                    meta: {file_type: 'video'}, //POST参数
                                    metaWithUrl: false,  // 将 meta 拼接到 url 参数中,默认 false
                                    headers: {Accept: 'text/x-json', admintoken: ''},// admintoken是否验证登录状态
                                    // 单个文件的最大体积限制,默认为 10M
                                    maxFileSize: 40 * 1024 * 1024,
                                    maxNumberOfFiles: 3,//最多可上传几个文件
                                    allowedFileTypes: ['video/*'],// 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
                                    // 上传之前触发
                                    onBeforeUpload(file) {
                                        return file
                                    },
                                    // 上传进度的回调函数
                                    onProgress(progress) {
                                    },
                                    // 单个文件上传成功之后
                                    onSuccess(file, res) {
                                    },
                                    // 单个文件上传失败
                                    onFailed(file, res) {
                                        alert(res.message)
                                    },
                                    // 上传错误,或者触发 timeout 超时
                                    onError(file, err, res) {
                                        alert(err.message)
                                    },
                                },
                                "uploadAttachment": {
                                    server: '../adminIsAdmin/js/editor/_up.php?act=main',
                                    timeout: 30 * 1000, // 上传时间
                                    fieldName: 'upfile',
                                    meta: {file_type: 'file'},
                                    metaWithUrl: false, // meta 拼接到 url 上
                                    headers: {Accept: 'text/x-json'},
                                    maxFileSize: 10 * 1024 * 1024, // 10M
                                    // 上传之前触发
                                    onBeforeUpload(file) {
                                        return file
                                    },
                                    // 上传进度的回调函数
                                    onProgress(progress) {
                                    },
                                    // 单个文件上传成功之后
                                    onSuccess(file, res) {
                                    },
                                    // 单个文件上传失败
                                    onFailed(file, res) {
                                        alert(res.message)
                                    },
                                    // 上传错误,或者触发 timeout 超时
                                    onError(file, err, res) {
                                        alert(err.message)
                                    },
                                }
                            },
                            onCreated(editor) {//初始化加载完成
                            },
                            onChange(editor) {
                                $("#body").val(editor.getHtml());
                            },
                        }
                    })

                    window.toolbar = E.createToolbar({
                        editor,
                        selector: '#editor-toolbar',
                        config: {
                            insertKeys: {
                                index: 0,
                                keys: [
                                    // "insertFormula", // “插入公式”菜单
                                    "kityFormula", // “编辑公式”菜单
                                    "uploadAttachment",//“附件”菜单
                                ],
                            },
                            // insertKeys: {
                            //     index: 24,
                            //     keys: [
                            //         "uploadAttachment",
                            //     ],
                            // },
                            excludeKeys: [
                                'codeBlock','undo','redo'
                            ]
                        }
                    })

                    // //查看当前工具栏排序和分组
                    //   const curToolbarConfig = window.toolbar.getConfig()
                    //   console.log(curToolbarConfig.toolbarKeys)
                </script>

_up.php上传处理文件

<?php
include("../../../adminIsAdmin/php_conn.php");
?>
<?php
set_time_limit(600);
$act = Ititle("get.act");
$infoArray = array();
$infoArray["errno"] = 0;
$infoArray["message"] = 'ok';
//sleep(1);
if ($act == "main" && empty($_FILES) === false) {
    if (!empty($_FILES['upfile']['error'])) {
        switch ($_FILES['upfile']['error']) {
            case '1':
                $error = '超过php.ini允许的大小。';
                break;
            case '2':
                $error = '超过表单允许的大小。';
                break;
            case '3':
                $error = '图片只有部分被上传。';
                break;
            case '4':
                $error = '请选择图片。';
                break;
            case '6':
                $error = '找不到临时目录。';
                break;
            case '7':
                $error = '写文件到硬盘出错。';
                break;
            case '8':
                $error = 'File upload stopped by extension。';
                break;
            case '999':
            default:
                $error = '未知错误。';
        }
        //Eleditor
        $infoArray["errno"] = 1;
        $infoArray["message"] = $error;
        $infoArray["_POST"] = $_POST;
    } else {
        $ext_arr = array(
            "image" => array("gif", "jpg", "jpeg", "png", "bmp"),
            "file" => array("rar", "zip", "tar", "gz", "7z", "bz2", "cab", "iso", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "txt", "md", "xml"),
            "music" => array("mp3"),
            "video" => array("mp4"),
        );
        $wjj_arr = array(
            "image" => "image/up_image/",
            "file" => "image/up_file/",
            "music" => "image/up_music/",
            "video" => "image/up_video/",
        );
        $php_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/';
        //$php_url = dirname($_SERVER['PHP_SELF']) . '/';
        $php_url = "" . $swtWjj . "/";
        $save_path = $php_path;
        $save_path = realpath($save_path) . '/';
        $file_name = $_FILES['upfile']['name'];
        $picsize = $_FILES['upfile']['size'];
        $tmp_name = $_FILES['upfile']['tmp_name'];
        $max_size = 1024 * 1024 * 10;
        $url_pic = $_POST["file_type"] ? $wjj_arr[$_POST["file_type"]] : 'image/';
        $arr_url = $php_url . $url_pic . date("Ymd") . "/";
        $pic_url = $save_path . $url_pic . date("Ymd") . "/";
        if (!file_exists($pic_url)) {
            mkdir($pic_url, 0777, true);
        }
        $dir_name = $_POST["file_type"] ? $_POST["file_type"] : 'image';
        if (!$file_name) {
            $infoArray = array();
            $infoArray["errno"] = 1;
            $infoArray["message"] = '请选择文件';
            $infoArray["_POST"] = $_POST;
            $infoArray["file"] = $_FILES;
            $josn = json_encode($infoArray, true);
            echo $josn;
            exit;
        }
        if (@is_dir($pic_url) === false) {
            $infoArray = array();
            $infoArray["errno"] = 1;
            $infoArray["message"] = '上传目录不存在';
            $infoArray["_POST"] = $_POST;
            $josn = json_encode($infoArray, true);
            echo $josn;
            exit;
        }
        if (@is_writable($pic_url) === false) {
            $infoArray = array();
            $infoArray["errno"] = 1;
            $infoArray["message"] = '上传目录没有写权限';
            $infoArray["_POST"] = $_POST;
            $josn = json_encode($infoArray, true);
            echo $josn;
            exit;
        }
        if ($picsize > $max_size) {
            $infoArray = array();
            $infoArray["errno"] = 1;
            $infoArray["message"] = '文件大小不能超过10M';
            $infoArray["_POST"] = $_POST;
            $josn = json_encode($infoArray, true);
            echo $josn;
            exit;
        }
        $temp_arr = explode(".", $file_name);
        $type_ext = array_pop($temp_arr);
        $type_ext = trim($type_ext);
        $type_ext = strtolower($type_ext);
        if (in_array($type_ext, $ext_arr[$dir_name]) === false) {
            $infoArray = array();
            $infoArray["errno"] = 1;
            $infoArray["message"] = '上传文件扩展名,只允许' . implode(",", $ext_arr[$dir_name]) . '格式';
            $infoArray["type_ext"] = $type_ext;
            $infoArray["ext_arr"] = $ext_arr;
            $infoArray["_POST"] = $_POST;
            $josn = json_encode($infoArray, true);
            echo $josn;
            exit;
        }
        $temp_arr = explode(".", $file_name);
        $new_file_name = $temp_arr[count($temp_arr) - 2];
        $new_file_name = $new_file_name;
        $new_file_name = "" . build_order_no() . "." . $type_ext;
        $pic_path = $pic_url . iconv('UTF-8', 'GB2312//IGNORE', $new_file_name);
        if (move_uploaded_file($tmp_name, $pic_path) === false) {
            $infoArray = array();
            $infoArray["errno"] = 1;
            $infoArray["message"] = '上传文件失败';
            $infoArray["_POST"] = $_POST;
            $josn = json_encode($infoArray, true);
            echo $josn;
            exit;
        }
        //图片尺寸压缩
        /*      if ($_POST["imageSizeCompression"] == "true" && is_numeric($_POST["w"]) && is_numeric($_POST["h"])) {
                  //图片尺寸处理
                  $picurl = $arr_url . $new_file_name;
                  $w = $_POST["w"];
                  $h = $_POST["h"];
                  $zoom_crop = $_POST["zoom_crop"] ? $_POST["zoom_crop"] : 1;
                  if ($picurl) {
                      $arr = explode('/', $picurl);
                      $num = count($arr);
                      $picurl_old = "" . $arr[$num - 4] . "/" . $arr[$num - 3] . "/" . $arr[$num - 2] . "/" . $arr[$num - 1] . "";
                      if (file_exists($picurl_old)) {
                          imgSmallFun_small($picurl_old, $picurl_old, $w, $h, '', $zoom_crop);
                      }
                  }
              }*/
        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态,上传成功时必须返回"errno"=0
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
         */
        $infoArray["errno"] = 0;
        $infoArray["message"] = "SUCCESS";
        $infoArray["_POST"] = $_POST;
        $infoArray["data"] = array();
        $infoArray["data"]["url"] = $arr_url . $new_file_name;
        $infoArray["data"]["alt"] = '';
        $infoArray["data"]["href"] = '';
    }
}
$josn = json_encode($infoArray, true);
echo $josn;
?>

引用文件统一放代码包了。行调整下引用路径就行

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值