首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Liferay 整合 TinyMCE 富文本編輯器:從中文化到圖片上傳完整落地指南

     編輯:Java 程式設計入門

項目背景與技術選型

Liferay 內置編輯器功能弱、擴展難。團隊選型 TinyMCE 2.0.8 (成熟穩定、插件豐富) 替換默認編輯器,Liferay 版本 liferay-portal-tomcat-4.1.2。核心挑戰:

  1. 中文化 & 中文字體支持
  2. 與 Liferay 深度集成 (替換默認編輯器實例)
  3. 擴展 advimage 插件實現**圖片上傳** (官方版僅支持外鏈)

一、TinyMCE 中文化與字體配置

1. 語言包部署

  1. 下載 tinymce_lpackage_zh-cn.jar 解壓至 {$LANGUAGE_PATH}
  2. 複製 {$LANGUAGE_PATH}/tinymce/jscripts/tiny_mce/* 到 Liferay {$LIFERAY_HOME}/webapps/ROOT/html/js/editor/tinymce/
  3. 修改 tinymce.jsp,在 tinyMCE.init({...}) 中添加:language : "zh_cn"

2. 字體下拉框添加中文字體

編輯 {$LIFERAY_HOME}/webapps/ROOT/html/js/editor/tinymce/themes/advanced/editor_template.js 和 simple/editor_template.js:

// 找到 var iFonts = '...' 和 var nFonts = '...'
var iFonts = 'Andale Mono=andale mono;Arial=arial;...;宋體=宋體;方正姚體=方正姚體;微軟雅黑=微軟雅黑';
var nFonts = 'Andale Mono=andale mono;Arial=arial;...;宋體=宋體;方正姚體=方正姚體;微軟雅黑=微軟雅黑';

格式:顯示名=CSS font-family 值,分號分隔。

二、Liferay 集成 TinyMCE 為默認編輯器

1. 部署 TinyMCE 靜態資源

# 解壓 tinymce_2_0_8.zip
cp -r tinymce/jscripts/tiny_mce {$LIFERAY_HOME}/webapps/ROOT/html/js/editor/tinymce

2. 修改編輯器選擇邏輯 (editor.jsp)

<%@ page import="com.liferay.portal.util.Constants" %>
<%@ page import="com.liferay.portal.util.PropsUtil" %>
<%@ page import="com.liferay.util.BrowserSniffer" %>
<%@ page import="com.liferay.util.ParamUtil" %>
<%
    String editorImpl = "simple";
    if (BrowserSniffer.is_rtf(request)) {
        editorImpl = ParamUtil.get(request, "editorImpl", PropsUtil.get(EDITOR_WYSIWYG_IMPL_KEY));
    }
    // 強制使用 tinymce
    editorImpl = "tinymce";

    RequestDispatcher rd = application.getRequestDispatcher(Constants.TEXT_HTML_DIR + "/js/editor/" + editorImpl + ".jsp");
    rd.include(request, response);
%>

或修改 system.properties:editor.wysiwyg.impl=tinymce。

三、核心難點:為 TinyMCE advimage 插件添加圖片上傳功能

架構:TinyMCE (前端) → JavaScript 彈窗 → Struts Action (後端上傳) → 返回圖片 URL → 填入編輯器。

1. 後端上傳組件 (Struts 1.x)

FileUploadForm.java (表單 Bean)

package com.family.fileupload.web.form;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class FileUploadForm extends ActionForm {
    private FormFile file;
    public FormFile getFile() { return file; }
    public void setFile(FormFile file) { this.file = file; }
}

FileUpload.java (工具類,處理流存儲)

package com.family.fileupload.web.utils;
import org.apache.struts.upload.FormFile;
import java.io.*;

public class FileUpload {
    private final FormFile file;
    private final String extendName;
    public FileUpload(FormFile file) {
        this.file = file;
        this.extendName = file.getFileName().substring(file.getFileName().lastIndexOf('.') + 1).toLowerCase();
    }
    public void saveToFile(String destPath) throws IOException {
        try (InputStream is = file.getInputStream();
             OutputStream os = new FileOutputStream(destPath)) {
            byte[] buf = new byte[8192];
            int len;
            while ((len = is.read(buf)) != -1) os.write(buf, 0, len);
        }
    }
    public String getExtendName() { return extendName; }
}

FileUploadAction.java (DispatchAction,處理上傳邏輯)

package com.family.fileupload.web.action;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.DispatchAction;
import com.family.fileupload.web.form.FileUploadForm;
import com.family.fileupload.web.utils.FileUpload;
import java.util.Calendar;
import java.util.Date;

public class FileUploadAction extends DispatchAction {
    public ActionForward uploadImage(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        FileUploadForm uploadForm = (FileUploadForm) form;
        FileUpload fu = new FileUpload(uploadForm.getFile());

        String realPath = getServlet().getServletContext().getRealPath("/pictures");
        String fileName = genTimestampName() + "." + fu.getExtendName();
        String filePath = realPath + "/" + fileName;
        fu.saveToFile(filePath);

        // 返回可訪問的 URL
        String fileUrl = getRootUrl(request) + "/pictures/" + fileName;
        request.setAttribute("fileUrl", fileUrl);
        return mapping.findForward("image.success");
    }

    private String genTimestampName() {
        Calendar c = Calendar.getInstance();
        return String.format("%tY%tm%td%tH%tM%tS", c, c, c, c, c, c); // yyyyMMddHHmmss
    }
    private String getRootUrl(HttpServletRequest req) {
        StringBuffer url = req.getRequestURL();
        url.delete(url.length() - req.getRequestURI().length(), url.length());
        return url.toString();
    }
}

2. 前端上傳頁面 (upload.jsp),放入 tinymce/plugins/advimage/

<form action="/c/portal/fileUpload?method=uploadImage" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上傳">
</form>

3. 回調頁面 (imagePath.jsp),放入 webapps/ROOT/html/

<script>
function insertImage() {
    var imageUrl = '<%=(String) request.getAttribute("fileUrl")%>';
    if (imageUrl) {
        opener.document.all("src").value = imageUrl; // 填入 TinyMCE 圖片對話框的 src 輸入框
        window.close();
    }
}
insertImage();
</script>

4. 修改 tinymce.jsp 注入文件瀏覽回調

function fileBrowserCallBack(field_name, url, type, win) {
    // 打開上傳頁面,寬高自定
    win.open("upload.jsp", "fileBrowser", "width=400,height=150,resizable=yes,scrollbars=yes");
}

並在 tinyMCE.init 中啟用:file_browser_callback : "fileBrowserCallBack"。

5. Struts 配置 (struts-config-ext.xml)

<form-beans>
    <form-bean name="fileUploadForm" type="com.family.fileupload.web.form.FileUploadForm" />
</form-beans>

<action-mappings>
    <action path="/portal/fileUpload"
            type="com.family.fileupload.web.action.FileUploadAction"
            name="fileUploadForm"
            scope="request"
            parameter="method">
        <forward name="image.success" path="/imagePath.jsp" />
    </action>
</action-mappings>

6. 打包部署

  1. 編譯上述 Java 類,打包為 upload.jar
  2. 放入 {$LIFERAY_HOME}/webapps/ROOT/WEB-INF/lib/
  3. 重啟 Tomcat

四、已知版本兼容性說明

  • Liferay 3.6.1:IE 下報 tinyMCE 未定義,Firefox 初始化極慢,圖片上傳文件損壞 —— **不推薦**
  • Liferay 4.1.2 + TinyMCE 2.0.8:本文驗證穩定可用 —— **推薦組合**

五、總結與擴展建議

  1. 上傳組件可獨立為單獨 WebApp,僅需調整 upload.jsp 的 action 指向獨立服務。
  2. 生產環境建議:文件類型白名單、大小限制、存儲雲存儲 (S3/OSS)、圖片壓縮/水印。
  3. TinyMCE 4.x/5.x 現代版本架構變化大,遷移時需重寫插件邏輯,但核心思路一致。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved