1. 程式人生 > 實用技巧 >jfinal 整合百度編輯器ueditor

jfinal 整合百度編輯器ueditor

>>> hot3.png

先來張效果圖

一,準備工作搭建好的jfinal 專案,百度編輯器官網下載ueditor和相應的java包

二,將ueditor編輯器複製貼上到專案目錄下,我的路徑是/webapp/static/plugins/ueditor

三,在ueditor中找到config.json,複製到ueditor根目錄下

四,在ueditor中找到ueditor.config.js,修改裡面的程式碼,將原來的jsp修改為自己寫的controller請求路徑

// , serverUrl: URL + "jsp/controller.jsp"
, serverUrl:serverURL+"/ueditor/index"

五,將百度提供的java類複製貼上到自己的專案目錄下,不需要修改任何內容,實現ueditor類的時候要用到

六,實現/ueditor/index,以下是該controller的實現類

import com.baidu.ueditor.ActionEnter;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.weixun.cms.service.SiteService;
import com.weixun.utils.ajax.AjaxMsg;
import com.weixun.utils.file.FileUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class UeditorController extends Controller {
    SiteService siteService = new SiteService();

    /**
     * ueditor初始化方法
     */
    public void index() {
//        String outText = ActionEnter.me().exec(getRequest());
        String rootPath = getRequest().getSession().getServletContext().getRealPath(File.separator+"static"+File.separator+"plugins"+File.separator);
        String outText = new ActionEnter(getRequest(),rootPath).exec();
        renderHtml(outText);
    }


    /**
     * 獲取儲存到資料庫中的路徑
     * 沒有則手動指定路徑
     * @return
     */
    private Record  getpath()
    {
        List<Record>  records =siteService.findList("");
        return records.get(0);
    }

    /**
     * 圖片上傳方法
     */
    public void upimage()
    {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Ret ret = null;
        try {
            //設定檔案上傳子目錄
            String path="uploads/images/";
            //獲取上傳的檔案
            UploadFile upload = getFile("upfile",path);
            File file = upload.getFile();
            //獲取檔名
            String extName = FileUtils.getFileExt(file.getName());
            //獲取檔案上傳的父目錄
            String filePath = upload.getUploadPath();
            //時間命名檔案
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + extName;
            //重新命名原來的檔案
            file.renameTo(new File(filePath+fileName));
            //重新組合檔案路徑  ip+檔案目錄+檔名
            String fileUrl=getpath().getStr("site_domain")+File.separator+path+fileName;

//            ajaxMsg.setState("success");
//            ajaxMsg.setMsg(fileUrl);
            ret = Ret.create("state", "SUCCESS")
                    .set("url", fileUrl)
                    .set("path",fileUrl)
                    .set("original", "")
                    .set("title",fileName);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setState("fail");
        }

        renderJson(ret);
    }

    /**
     * 視訊上傳方法
     */
    public void upvideo()
    {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Ret ret = null;
        try {
            //設定檔案上傳子目錄
            String path="uploads/videos/";
            //獲取上傳的檔案
            UploadFile upload = getFile("upfile",path);
            File file = upload.getFile();
            //獲取檔名
            String extName = FileUtils.getFileExt(file.getName());
            //獲取檔案上傳的父目錄
            String filePath = upload.getUploadPath();
            //時間命名檔案
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + extName;
            //重新命名原來的檔案
            file.renameTo(new File(filePath+fileName));
            //重新組合檔案路徑  ip+檔案目錄+檔名
            String fileUrl=getpath().getStr("site_domain")+File.separator+path+fileName;

//            ajaxMsg.setState("success");
//            ajaxMsg.setMsg(fileUrl);
            ret = Ret.create("state", "SUCCESS")
                    .set("url", fileUrl)
                    .set("path",fileUrl)
                    .set("original", "")
                    .set("title",fileName);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setState("fail");
        }

        renderJson(ret);
    }

    /**
     * 檔案上傳方法
     */
    public void upfile()
    {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Ret ret = null;
        try {
            //設定檔案上傳子目錄
            String path="uploads/files/";
            //獲取上傳的檔案
            UploadFile upload = getFile("upfile",path);
            File file = upload.getFile();
            //獲取檔名
            String extName = FileUtils.getFileExt(file.getName());
            //獲取檔案上傳的父目錄
            String filePath = upload.getUploadPath();
            //時間命名檔案
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + extName;
            //重新命名原來的檔案
            file.renameTo(new File(filePath+fileName));
            //重新組合檔案路徑  ip+檔案目錄+檔名
            String fileUrl=getpath().getStr("site_domain")+File.separator+path+fileName;

//            ajaxMsg.setState("success");
//            ajaxMsg.setMsg(fileUrl);
             ret = Ret.create("state", "SUCCESS")
                    .set("url", fileUrl)
                    .set("path",fileUrl)
                    .set("original", "")
                    .set("title",fileName);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setState("fail");
        }

        renderJson(ret);
    }


    /**
     * ueditor上傳
     */
    public void config(){
        if ("config".equals(getPara("action"))) {
            render("/static/plugins/ueditor/config.json");
            return;
        }
        UploadFile file = getFile("upfile");
        String fileName = file.getFileName();
        String[] typeArr = fileName.split("\\.");
        String orig = file.getOriginalFileName();
        long size = file.getFile().length();
//        String url = UploadOSSKit.uploadImage(file);
        String url="";
        Ret ret = Ret.create("state", "SUCCESS")
                .set("url", url)
                .set("path",url)
                .set("original", orig)
                .set("type", "."+typeArr[1])
                .set("size", size);
        renderJson(ret);
    }
    
}

七,在jsp頁面引入ueditor,初始化後指定上傳檔案,圖片,視訊的方法

<html>
<head>
    <meta charset="UTF-8"/>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">


    <title>後臺管理系統</title>
    <% String path = request.getContextPath(); %>
    <% Date d = new Date();%>
    <% SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小時制  %>
    <%String date = sdformat.format(d); %>
    <link rel="stylesheet" href="${basePath}/static/plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${basePath}/static/css/ztree/metro/ztree.css"  media="all">

    <%--百度編輯器需要引入的js--%>
    <script type="text/javascript" charset="utf-8" src="../../../static/plugins/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="../../../static/plugins/ueditor/ueditor.all.js"> </script>
    <!--建議手動加在語言,避免在ie下有時因為載入語言失敗導致編輯器載入失敗-->
    <!--這裡載入的語言檔案會覆蓋你在配置專案裡新增的語言型別,比如你在配置專案裡配置的是英文,這裡載入的中文,那最後就是中文-->
    <script type="text/javascript" charset="utf-8" src="../../../static/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>
    <style>
        .admin-main{
            height: 900px;
        }
        .mainLeft{
            float: left;
        }
        .mainRight{
            float: left;
        }
    </style>

</head>
<body>
<div class="admin-main">
    <div class="mainLeft">
    <form id="articleForm" method="post" class="layui-form" action="">
           <input id="article_pk" name="article_pk" type="hidden" />

           <div class="layui-form-item" style="margin-top:2%;">
               <label class="layui-form-label">標題</label>
               <div class="layui-input-inline">
                   <input id="article_title" name="article_title"  lay-verify="required"  autocomplete="off" placeholder="請輸入標題" class="layui-input" type="text" />
               </div>

               <label class="layui-form-label">圖片</label>
               <div class="layui-input-inline">
                   <img id="images" src="" width="190px" height="45px" title="">
               </div>

               <label class="layui-form-label">圖片</label>
               <div class="layui-input-inline">
                   <input id="article_titleimg" name="article_titleimg"  autocomplete="off"  class="layui-input" type="hidden"/>
                   <button type="button" class="layui-btn" id="file">
                       <i class="layui-icon">&#xe67c;</i>上傳圖片
                   </button>
               </div>

           </div>

            <div class="layui-form-item">

                <label class="layui-form-label">連結</label>
                <div class="layui-input-inline">
                    <input id="article_url" name="article_url"  lay-verify="required"  autocomplete="off" placeholder="請輸入連結" class="layui-input" type="text" />
                </div>

                <label class="layui-form-label">發文日期</label>
                <div class="layui-input-inline">
                    <input value="" id="article_sendtime" name="article_sendtime" class="layui-input" >
                </div>

            </div>
            <div align="center">
                <textarea id="editor" name="editor" style="margin-top:2%;padding:0;width:890px;height:650px;"></textarea>
            </div>

    </form>
</div>
    <%--樹形選單--%>
<div class="mainRight">
    <div align="center" class="layui-input-block" style="margin: 5% auto">
        <button class="layui-btn layui-btn-small" align="center" id="edit">儲存</button>
        <%--<button class="layui-btn layui-btn-small" align="center" id="send">釋出</button>--%>
    </div>
    <fieldset class="layui-elem-field layui-field-title">
        <legend>選單</legend>
    </fieldset>
    <ul id="ztree" class="ztree" style="display: inline-block; width: 170px; height: 750px; padding: 10px; border: 1px solid #ddd; overflow: auto;">
    </ul>
</div>
</div>
</body>

<script>
    /**
     * 初始化百度編輯器
     *
     * */
    var ue = UE.getEditor('editor', {
        autoHeight:true,
        autoHeightEnabled: false,//是否自動長高
        autoFloatEnabled: false,//浮動是離瀏覽器的高度
        imageScaledEnable:true,//圖片能否自動縮放
        allowDivTransToP:false//是否容許div轉換為p 標籤
//        enterTag : 'br'
    });
    /**
     * 設定百度編輯器上傳action
     *
     * */
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
        console.log("action"+action)
        if (action == 'uploadimage' || action == 'uploadscrawl' ) {
            return '<%=path%>/ueditor/upimage';
        }else if (action == 'uploadvideo')
        {
            return '<%=path%>/ueditor/upvideo';
        }
        else if (action == 'uploadfile')
        {
            return '<%=path%>/ueditor/upfile';
        }
        else {
            return this._bkGetActionUrl.call(this, action);
        }
    };
</script>

通過以上幾個步驟,jfinal中就整合好百度編輯器了,以下是我使用jfinal 採用多模組的方式實現的一個cms,以及整合了shiro,ueditor,layui

地址為:https://gitee.com/live.cn/wxcms

轉載於:https://my.oschina.net/mayude/blog/1796637