`

UEditor初步使用小结

阅读更多

最近公司项目中需要做一个简易的BBS论坛,相应的就需要富文本编辑器,之前使用过CFeditor,但UI总感觉不适合个人喜爱,经过对比后选择了百度开源的UEditor。

 

UEditor官网地址:http://ueditor.baidu.com/website/

 

目前最新版本:1.4.3,以下使用及配置都是基于此版本。我们使用的是jsp版本,以下为默认目录:



 进入jsp目录,我们可以看到ueditor所需要依赖的包,以及统一处理入口controller.jsp,还有对应请求配置,主要是涉及上传图片,视频,文件等;

 

将ueditor引入eclipse的web工程中



 

由于项目中使用maven工程,需要将依赖的jar配置到pom.xml中


 

 

一、配置

1. 定义页面展现的对象

<script id="message" name="message" type="text/plain">

 

<textarea id="message"></textarea>

 

2. 引入UEditor的JS文件

<script type="text/javascript" src="${contextPath}/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="${contextPath}/ueditor/ueditor.all.min.js"></script>

 

 3. 根据实际情况,修改相应的配置

<script type="text/javascript">
// 定义UEditor对应的主目录
window.UEDITOR_HOME_URL = "${contextPath}/ueditor/";
// 页面加载完成后载入UEditor
window.onload = function () {
	window.UEDITOR_CONFIG.initialFrameWidth = 1600;
	window.UEDITOR_CONFIG.initialFrameHeight = 600;
	UE.getEditor("message");
}
</script>

 

4. 运行所在的WEB应用,浏览相应的页面就可以看到UEditor效果;



 

5. 可以根据实际需要对富文本进行精简

 

window.UEDITOR_CONFIG.toolbars = [[
	                                   'fullscreen', 'source', '|', 'undo', 'redo', '|',
	                                   'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
	                                   'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
	                                   'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
	                                   'directionalityltr', 'directionalityrtl', 'indent', '|',
	                                   'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
	                                   'link', 'unlink', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
	                                   'insertimage', 'insertvideo', 'emotion', 'pagebreak', '|',
	                                   'horizontal', 'date', 'time', 'spechars', '|',
	                                   'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
	                                   'preview', 'searchreplace'
	                               ]];

 

6. 自定义请求地址,ueditor 1.4.2+ 推荐使用唯一的请求地址,通过GET参数action指定不同请求类型,但往往在实际开发中,我们需要自己定义图片或其它附件上传逻辑。UEditor默认上传目录为ueditor主目录/ueditor/jsp/upload/image/文件名,这里我们使用自己实现的文件上传逻辑,依赖spring mvc,以下为示例代码:

spring mvc 配置

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- 自动扫描且只扫描@Controller -->
	<context:component-scan base-package="net.jforum.view.forum"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
		<context:include-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
	</context:component-scan>

	<mvc:annotation-driven
		content-negotiation-manager="contentNegotiationManager">
		<mvc:message-converters register-defaults="true">
			<!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<constructor-arg value="UTF-8" />
			</bean>
			<!-- 将Jackson2HttpMessageConverter的默认格式化输出设为true -->
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="prettyPrint" value="true" />
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

	<!-- REST中根据URL后缀自动判定Content-Type及相应的View -->
	<bean id="contentNegotiationManager"
		class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
		<property name="mediaTypes">
			<value>
				json=application/json
				xml=application/xml
			</value>
		</property>
	</bean>

	<!-- 容器默认的DefaultServletHandler处理 所有静态内容与无RequestMapping处理的URL -->
	<mvc:default-servlet-handler />

	<!-- 定义无需Controller的url<->view直接映射 -->
	<mvc:view-controller path="/" view-name="index" />
	
	<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 指定所上传文件的总大小不能超过6M。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
        <property name="maxUploadSize" value="6291456"/>
        <property name="resolveLazily" value="true"/>
    </bean>

</beans>
      图片上传:

 

 

    private static Logger logger = Logger.getLogger(UeditorAction.class);

    private ObjectMapper  mapper = new ObjectMapper();

    @RequestMapping(value = "uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public String uploadImage(@RequestParam("upfile") MultipartFile file, HttpServletRequest request,
            HttpServletResponse response) {
        String output = "";
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            Map<String, Object> userInfo = SSOUserUtil.getPrincipal(request);
            String userId = String.valueOf(userInfo.get(IUser.USER_ID));
            String filePath = FilePathUtil.getUploadFullPath(String.valueOf(userId),
                    uuid + fileName.substring(fileName.lastIndexOf(".")));
            FileUtil.uploadFile(filePath, file.getInputStream());

            String url = Base64.encodeBase64String(filePath.getBytes("UTF-8"));
            result.put("url", HttpServletUtil.getServerName(request) + "/ueditor/getImage/" + url);
            result.put("original", fileName);
            result.put("size", file.getSize());
            result.put("type", fileName.substring(fileName.lastIndexOf(".")));
            result.put("state", "SUCCESS");

            output = mapper.writeValueAsString(result);
        } catch (Exception e) {
            logger.error("ueditor image upload error : ", e);
        }

        return output;
    }
     页面图片上传请求地址:

 

 

   UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
	UE.Editor.prototype.getActionUrl = function(action) {
	    if (action == "uploadimage") {
	        return "${contextPath}/ueditor/uploadImage";
	    } else {
	        return this._bkGetActionUrl.call(this, action);
	    }
	}
     图片获取:

 

 

    @RequestMapping(value = "getImage/{path}", method = RequestMethod.GET)
    public void getImage(@PathVariable String path, HttpServletRequest request, HttpServletResponse response) {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            path = new String(Base64.decodeBase64(path), "UTF-8");
            fis = new FileInputStream(path);
            os = response.getOutputStream();
            int c;
            byte[] b = new byte[4096];
            while ((c = fis.read(b)) != -1) {
                os.write(b, 0, c);
            }
            os.flush();
        } catch (Exception e) {
            logger.error("ueditor get image error : ", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {

                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {

                }
            }
        }
    }
 到此图片上传OK。


 

 

 

 

 

二、 问题:

由于这个论坛只是公司项目中的一个子项目,且此工程需要集成到一个信息门户CMS中,在现有项目中是通过iframe的方式将这个工程内嵌到信息门户CMS的,这里会遇到iframe跨域的问题,好在我们的项目是集成部署的,最终配置的域名统一,例如信息门户CMS地址为www.test.com,论坛地址:bbs.test.com,他们的根域都是test.com,所以在集成中通过设置document.domain来解决跨域造成的iframe高度自适应问题

 

document.domain = "test.com";

 

具体代码如下:

a. 在信息门户CMS的iframe所在页面中设置域名

 

document.domain = "test.com";
b. 在信息门户CMS中创建共用JS,由第三应用(这里就是BBS论坛)调用这个JS文件,我们这里默认称它为代理JS,取名为agent.js,只有一句话;

 

 

document.domain = "test.com";
c. 在BBS论坛中,在公用页面引用agent.js

 

 

<script type="text/javascript" src="http://www.test.com/agent.js"></script>
d.这样就解决了iframe的跨域问题,可以互相访问对方应用页面中的document对象,我们这里需要解决的是iframe跨域高度自适应的问题,那么我们就可以在CMS页面onload时,通过获取iframe页面中的实际高度来设置iframe具体的高度。

 

<iframe id="iframeB" name="iframeB" width="100%"
				src="http://bbs.test.com/1.html" allowtransparency="yes" frameborder="false"
				scrolling="no" onload="initSalon(this)"></iframe>

 

function reinitIframe() {
			var iframe = document.getElementById("iframeB");
			try {
				var bHeight = iframe.contentWindow.document.body.scrollHeight;
				var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
				var height = Math.max(bHeight, dHeight);
				iframe.style.height = height + "px";
			} catch (ex) {

			}
		}

 

e. 但后面的问题又来了,iframe中的页面的高度是不断变化的,所以我们又需要根据iframe的高度变化来动态改变CMS页面的高度,此时我们可以通过setInterval动态个性iframe的高度

 

setInterval(reinitIframe, 200);

 

f. 我们默认设置iframe的初始高度小一些,这样比较明显

 

function initSalon(e) {
			e.style.height = '450px';
		}

 

g. 这里我们是解决的iframe跨同子域的问题,如何实现完全跨域的iframe高度自适应的问题,可以参照链接:

http://www.cnblogs.com/snandy/p/3902337.html

http://www.cnblogs.com/snandy/p/3900016.html

http://zoujialiang.iteye.com/blog/682216

http://cued.xunlei.com/log019

http://blog.sina.com.cn/s/blog_63940ce201015w0d.html

http://caibaojian.com/iframe-adjust-content-height.html

 

再回到我们的UEditor,由于内嵌在CMS中的页面设置了document.domain = “test.com”,而我们的UEditor上传图片,上传视频等 ,需要新打开一个窗口,且窗口是通过iframe进行加载的,这里初步的弹出窗口域名为bbs.test.com,两者不在一个域名下,此时我们的UEditor就无法正常使用,此时我们就得个性UEditor默认的配置

a. 修改ueditor/dialogs/internal.js文件,在第一行,即在var parent = window.parent;上方增加:document.domain = “test.com”,但此时只能解决在chrome和firefox中跨域的问题,但在IE在还是无法使用,提示“没有权限”,此时我们需要再修改editor.all.js

将:

src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ?  'document.domain="' + document.domain + '";' : '') +
                        'document.write("' + html + '");document.close();}())'

 修改为:

src: 'javascript:void(function(){document.open();' + 'document.domain="test.com"' +
                        'document.write("' + html + '");document.close();}())'

 同时在方法Editor.prototype._setup中me.document = doc;下方增加document.domain = “test.com"。



 



 

 

至此终于解决了跨子域的问题,可以正常上传图片,上传在线视频等。



 

 

 

  • 大小: 32.2 KB
  • 大小: 25.1 KB
  • 大小: 24.8 KB
  • 大小: 17.6 KB
  • 大小: 26.6 KB
  • 大小: 52.8 KB
  • 大小: 381.7 KB
  • 大小: 67 KB
  • 大小: 96.6 KB
  • 大小: 80.9 KB
  • 大小: 191.7 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics