您的位置:首页 > 产品设计 > UI/UE

百度ueditor使用心得

2017-11-26 21:02 267 查看
      富文本编辑器,相信很多人在开发新闻发布类的网站的时候难免用到富文本编辑器,这个HTML神器可以发布类似word中的布局的功能,又可以插入图片,视频等,备受青睐!

首先来说说他的具体使用,然后再说说使用时遇到的坑吧!

使用与心得:

首先在官网上下载ueditor,本人下载的是jsp版本,目录大致结构如下:



然后是在使用的页面中引入,jsp页面代码如下:

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/manage/common/taglibs.jsp"%>
<script type="text/javascript"src="${ctx}/manage/ueditor/ueditor.config.js"></script>
<script type="text/javascript"src="${ctx}/manage/ueditor/ueditor.all.js"></script>
<style>
.upd_table  {
padding:10px;
margin-top:5px;
}

.upd_table  td input {
width:70%;
}

</style>
<form id="knowledgeEditForm" method="post" class="admin_form_inputs">
<table align="center" id="knowledgetab" class="upd_table" style="line-height:27px;width:100%" cellSpacing=0 cellPadding=0 width="98%" align=center border=0>
<tr bgcolor=#ffffff onmouseover="this.bgColor='#f3f3f3';" onmouseout="this.bgColor='#ffffff';" width="100%">
<td width="20%" align="right">
活动标题:
</td>
<td width="80%">
<input type="hidden" name="id" value="${knowledgeUser.id}" id="id" class="easyui-validatebox" />
<input type="text" name="title" value="${knowledgeUser.title}" id="title" class="easyui-validatebox" maxlength="60"/>
<span style="color:red">*</span>
</td>
</tr>

<tr bgcolor=#ffffff onmouseover="this.bgColor='#f3f3f3';" onmouseout="this.bgColor='#ffffff';" width="100%">
<td width="20%" align="right">
正文内容:
</td>
<td width="80%">
<div style="display:none;"><!-- 隐藏的text里面是html的在页面还是显示 -->
<input type="hidden" id="content"  name="content" value="${knowledgeUser.content}"/>
</div>
<div style="align-center;z-index:99999;width:100%;height:100%;">
<iframe id="content_ue_frm"  src="${ctx}/manage/ueditor.honzh" marginheight="0" marginwidth="0" frameborder="0"  style="align:center;left: 10px; top:0px;width:98%;height:460px;"></iframe>
</div>
<span style="color:red">*</span>
</td>
</tr>
<tr bgcolor=#ffffff onmouseover="this.bgColor='#f3f3f3';" onmouseout="this.bgColor='#ffffff';" width="100%">
<td colspan="2" align="center">
<c:if test="${toolsbtn=='tijiao'}">
<a href="#" onclick="javascript:save('2')" class="easyui-linkbutton">提交</a>
</c:if>
<c:if test="${toolsbtn=='baocun'}">
<a href="#" onclick="javascript:save('3')" class="easyui-linkbutton">保存</a>
</c:if>
<a href="#" onclick="javascript:clean()" class="easyui-linkbutton">清空</a>
</td>
</tr>
</table>
</form>

<script type="text/javascript">
//清空
function clean(){
//	$("#knowledgeEditForm").form("clear");
document.getElementById("title").value = "";
document.getElementById("content").value = "";
}

function __getContent() {
var content = '${knowledgeUser.content}';
return content;
}

//提交保存
function save(flag_id){
var id=$("#id").val();
var title=$("#title").val();
//		var content=$("#content").val();

var content1= '';//$("#content").val();
try {
// iframe获取
var ue_FrmObj = document.getElementById('content_ue_frm');
var ue_FrmWin = ue_FrmObj.contentWindow;
content1 = ue_FrmWin.getUeContent();//.editor.getContent();
$('#content').val(content1);
} catch (e) {
//alert('err');
}
var content=$("#content").val();
if(title==""){
agAlert("新闻标题不能为空!");
return;
}
if(mts_illeagal(title)){
title("新闻标题含有非法字符!");
}
if(content==""){
agAlert("正文内容不能为空!");
return;
}
//验证正文不能输入特殊字符
//if(mts_illeagal(content)){
//	title("标题含有非法字符!");
//}

$.messager.confirm('提示', '确定要保存吗?',function(r){
if(r){
$("#knowledgeEditForm").form('submit',{
url:'${ctx}/manage/doUpdateKnowledgeServer.honzh?id='+id+'&flag_id='+flag_id,
onSubmit : function () {
$.messager.progress();
},
success: function (txt) {
$.messager.progress('close');
var result = eval('('+txt+')');
if(result.success){
$.messager.show({
title: '提示信息',
msg: '保存成功',
timeout: 3000
});
$("#winopenKnowledgeEdit").window("close");
$("#knowledge_list").datagrid('reload');
}else{
$.messager.show({
title: '提示信息',
msg: '保存失败',
timeout: 3000
});
}
}
});
}
});
}
</script>

<script type="text/javascript">
$(function(){

});
</script>


从上面代码中可以看到这一部分代码:

<div style="align-center;z-index:99999;width:100%;height:100%;">
<iframe id="content_ue_frm"  src="${ctx}/manage/ueditor.honzh" marginheight="0" marginwidth="0" frameborder="0"  style="align:center;left: 10px; top:0px;width:98%;height:460px;"></iframe>
</div>


其中ueditor类的代码如下:

public void ueditor(){
System.out.println("ueditor");
render("content/ueditor/ueditor.jsp");
}


而ueditor.jsp页面的代码如下:

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/manage/common/taglibs.jsp"%>

<script type="text/javascript" src="${ctx}/manage/jquery-easyui/jquery.min.js"></script>

<script type="text/javascript">
</script>

<script type="text/javascript"src="${ctx}/manage/ueditor/ueditor.config.js"></script>
<script type="text/javascript"src="${ctx}/manage/ueditor/ueditor.all.js"></script>
<script type="text/javascript"src="${ctx}/manage/ueditor/lang/zh-cn/zh-cn.js"></script>

<script type="text/javascript">
var editor ;

UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
return '${ctx}/manage/uploadUeditor.honzh';
} else if (action == 'uploadvideo') {
//       return '${ctx}/cms/file/uploadUeditorVideo.action';
return '${ctx}/manage/uploadUeditorVideo.honzh';
} else {
return this._bkGetActionUrl.call(this, action);
}
};
$(function(){
//var editor=new UE.ui.Editor();

var initialContent = window.parent.__getContent();
editor = new UE.ui.Editor({
//这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
toolbars: [[
'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', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'insertimage','insertvideo'
]],
// toolbars:[[ 'FullScreen','Source','Undo','Redo','Bold','Italic','RemoveFormat','PastePlain','ForeColor','BackColor','FontFamily','FontSize','JustifyLeft','JustifyCenter','JustifyRight','JustifyJustify']],
//focus时自动清空初始化时的内容
// autoClearinitialContent:true,
//关闭字数统计
wordCount:false,
//关闭elementPath
elementPathEnabled:false,
compressSide:1 ,
maxImageSideLength:600,
autoHeightEnabled:false,
textarea: 'item_rele' ,
initialContent : initialContent
//更多其他参数,请参考editor_config.js中的配置项

});
editor.render("contentEditor");
});

function getUeContent() {
editor.sync();

var content_b = editor.getContent();
//	alert( content_b );
return content_b;
}

</script>

<div style="align-center;z-index:99999;width:100%;height:100%; "  >
<textarea id="contentEditor" name="content"  cols="100" rows="10" style="width:95%"></textarea>
</div>


上传到后台处理的代码如下:

@Before({OAuth2Interceptor1.class,Tx.class})
public void doUpdateKnowledgeServer(){
String flag_id = getPara("flag_id");
String id = getPara("id");
String title = getPara("title");
String userId = getSessionAttr("roleId");
String content = getPara("content");
Map<String,Object> map = new HashMap<String, Object>();
try {
if("2".equals(flag_id)){
//提交
News knowledge = getModel(News.class);
knowledge.set("title", title);
knowledge.set("user_id", userId);
knowledge.set("content", content);
knowledge.set("create_time", DateUtil.getFullTime());
knowledge.save();

}else if("3".equals(flag_id)){
//保存
News knowledge = News.dao.findById(id);
knowledge.set("title", title);
knowledge.set("user_id", userId);
knowledge.set("content", content);
knowledge.set("create_time", DateUtil.getFullTime());
knowledge.update();
}
map.put("success", true);
map.put("message", "保存成功!");
} catch (Exception e) {
e.printStackTrace();
map.put("success", false);
map.put("message", e.getMessage());
}
renderJson(map);
}


很简单的代码,毫无复杂度。

其中使用编辑器插入图片的代码,就是在ueditor.jsp中配置的后台处理路径 return '${ctx}/manage/uploadUeditor.honzh';如下:

public void uploadUeditor(){
Map<String,Object> map = new HashMap<String,Object>();
try {
String path = PathKit.getWebRootPath();
String str = path.substring(path.length()-1, path.length());
if(str.equals("/") || str.equals("\\")){
path = path.substring(0, path.length()-1) +
"Files/ueditor/" + DateUtil.dateToString(new Date());
} else {
path = path + "Files/ueditor/" + DateUtil.dateToString(new Date());
}

HttpServletRequest request = getRequest();
MultipartParser mp;
mp = new MultipartParser(request, 50*1024*1024, false, false, "utf-8");
Part part = null;

List<String> list = new ArrayList<String>();
while((part=mp.readNextPart())!=null){
if(part.isParam()){
}else if(part.isFile()){
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if(!"".equals(fileName) && !"null".equals(fileName) && fileName!=null){
String newFileName = System.currentTimeMillis() +
fileName.substring(fileName.lastIndexOf('.'), fileName.length());
writeFile(filePart.getInputStream(), path, newFileName);
list.add(DateUtil.dateToString(new Date())+"/"+newFileName);

map.put("name", fileName);
map.put("type", fileName.substring(fileName.lastIndexOf('.'), fileName.length()));
} else {
list.add("null");
}
}
}
for(int i=0;i<list.size();i++){
System.out.println("baga:"+list.get(i));
}
map.put("size", "");
map.put("url", list.get(0));
map.put("state", "SUCCESS");
} catch (Exception e) {
map.put("state", "false");
e.printStackTrace();
}
System.out.println(JsonKit.toJson(map));
renderJson(map);
}


这里要说明的是返回的图片上传的json格式为:

{"name":"0.gif","state":"SUCCESS","original":"0.gif","type":".gif","url":"http://IP地址:端口号/项目名/一直到图片的地址","size":""}

其中state的值一定要为SUCCESS否则编辑器不提示成功!

对此注意到url的值为绝对地址,这时就想到如果项目由一台服务器迁移到另一台服务器时,IP换了,这样存储在原来服务器上的数据库存储的还是原来服务器的文件资源,不是指向新服务器的,故此处将其改为相对地址,代码如上,已经是修改过的地址,;单还需要在编辑器的内部配置一下才行,配置如下:

打开ueditor/jsp/config.json文件,修改如下:




经在网上查阅得到上传视频需给编辑器返回的json为:

/**

* 得到上传文件所对应的各个参数,数组结构

* array(

* "state" => "", //上传状态,上传成功时必须返回"SUCCESS"

* "url" => "", //返回的地址

* "title" => "", //新文件名

* "original" => "", //原始文件名

* "type" => "" //文件类型

* "size" => "", //文件大小

* )

*/

后台示例代码如下:
public void uploadUeditorVideo(){
Map<String,Object> map = new HashMap<String,Object>();
try {
map.put("name", "0.mp4");
map.put("type", ".mp4");
map.put("size", "");
map.put("url", "20171126/132.mp4");
map.put("state", "SUCCESS");
} catch (Exception e) {
e.printStackTrace();
}
renderJson(map);
}


这样一来无论是你通过使用QQ截图通过复制粘贴的方式还是插入图片、插入视频的方式都可以上传你的图片视频。

但是上传视频的遇到了另一个小坑:
就是添加了视频,能够上传,但是在编辑器内显示的为一片空白:
跟这位网友的情况几乎完全相同:http://blog.csdn.net/eadela/article/details/76264168

后参照这位网友所说的修改成功,但是行数不对,特此记录如下,修改ueditor.all.js文件如下:





这样一来视频确实是显示了,但是效果并没有想象的好,因为视频无法预览,无法预览,无法预览,可以播放,可以播放,至少是能够辨别出是视频了,呵呵,后续仍要完全修复这个坑

网上也有人说修改whiteList的,但是由于本人使用版本(1.1.1版本)较低,并没有找到这个whiteList代码。。。

此外使用ueditor还遇到的另外一个坑是controller.jsp控制台总是报错,类似于如下错误:

An error occurred at line: 11 in the jsp file: /jsp/controller.jsp
ActionEnter cannot be resolved to a type
8:
9: 	String rootPath = application.getRealPath( "/" );
10:
11: 	out.write( new ActionEnter( request, rootPath ).exec() );
12:
13: %>
一旦出现此种错误,图片和视频均无法上传,;

解决的办法是将ueditor/jsp/lib下面的五个jar包添加到系统变量中:



并且要重新clean项目,重新clean项目,重新clean项目,然后发布,启动服务器,清空浏览器缓存,测试,通过,理论上就没有错误了!

并且一般走到这一步几乎也就没有什么错误了!

但是不幸的是我的还有错误,还是报错,但是这次的报错确实ueditor-1.1.1.jar报错,这个jar包报错,不知道什么原因;

于是重新从官网下载1.2版本,发现没有了任何错误,故猜想可能是jar包损坏或者不兼容等原因,于是将新下载的ueditor中的五个jar包全部替换原来的五个jar包,发现这次最终什么问题也没有了!

另外一个坑,就是在本地测试的时候没有出现任何问题,上传图片,视频均可以,但是打成war包发布到服务器的时候在上传图片和视频的时候显示“后端没有正常配置,等错误,于是查阅相关资料有的说是在服务端修改IP地址等配置信息的时候编码格式出错,需要在本地修改按照服务器的配置修改好配置信息,但经测试无效,最终找到的一个解决办法如下:

2.UEditor富文本编辑器中的多图上传提示“后端配置项没有正常加载,上传插件不能正常使用”的问题,查询谷歌后得到一个有效的解决方案:


打开 ueditor/jsp/lib 路径,把 lib 下的所有 jar 包全部复制到工程项目 WEB-INF/lib 下,然后我们在打开上传图片界面,点击选择图片按钮出现了。

至此上传问题解决,但是此时却出现了上传完成后确认按钮无法点击了,不知道是什么情况,于是决定重新按套路检查一遍项目,发现是由于原来添加进项目路径的ueditor的jar包被移除了,于是重新添加进项目路径,发现即使没有2的操作也是可以的,原来费了这么大劲儿,问题出现在了这里,真是失误,至此部署到服务器上的所有问题解决!

补充方法:

public boolean writeFile(InputStream inputStream, String savePath, String fileName){
try {
File file = new File(savePath);
if(!file.exists() && !file.isDirectory()){
file.mkdirs();
}
savePath=savePath+"/"+fileName;
//		System.out.println("savePath:"+savePath);
FileOutputStream fw = new FileOutputStream(savePath,true);
byte[] b = new byte[1024];
while(inputStream.read(b) != -1){
fw.write(b);
}
fw.flush();
fw.close();
return true;
} catch(IOException e) {
e.printStackTrace();
}
return false;
}


此外还有一个急需解决暂未解决的问题,就是如果插入了图片或者视频,均会保存在服务器上,而如果这篇文章没有最终提交到数据库,那么这些文件还是存在了服务器占用了服务器的空间,这种情况下如何使它不占用服务器的空间呢?另外一种情况就是这篇文章上传提交到了服务器,文件信息存储在数据库中,如果需要删除这篇文章的时候如何连通文件一同删除呢?后续抽空解决此问题!

虽仍是一技术菜鸟,却愿与技术人共同进步,企业交流群:589847567

内有源码共享!

参考文章:
https://www.zhihu.com/question/27656740 http://blog.csdn.net/eadela/article/details/76264168 http://bbs.csdn.net/topics/391963518
http://blog.csdn.net/eadela/article/details/76169660
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: