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

百度富文本编辑器ueditor使用小结

2016-08-17 15:52 483 查看
百度富文本编辑器ueditor使用小结

最近做的项目用到了文本编辑器,左右思量后我决定采用百度ueditor,因为他插入图片时不会弹出很繁琐的框,除非你添加的是多张,但也觉得比其他插件好看,而且在chrom浏览器里也支持剪切粘贴,以及拖拽(firefox浏览器也支持)图片方式。但是他的一些配置文档对初次使用者来说很难以理解,故作此总结。

1.ueditor 官方地址:http://ueditor.baidu.com/website/index.html

   开发文档地址:http://ueditor.baidu.com/website/document.html

   下载地址:http://ueditor.baidu.com/website/download.html (这里可选开发版,或MINI版)



本人选了jsp完整版本。

2. 从官网上下载完整源码包,解压到任意目录,解压后的源码目录结构如下所示:

     _examples:编辑器完整版的示例页面

    dialogs:弹出对话框对应的资源和JS文件

    themes:样式图片和样式文件   php/jsp/.net:涉及到服务器端操作的后台文件,根据你选择的不同后台版本,这里也会不同,这里我们选择php

    third-party:第三方插件(包括代码高亮,源码编辑等组件)

    editor_all.js:_src目录下所有文件的打包文件(用于发布版本)

    editor_api.js: API接口配置文件(开发版本)

    editor_all_min.js:editor_all.js文件的压缩版,建议在正式部署时才采用

    editor_config.js:编辑器的配置文件,建议和编辑器实例化页面置于同一目录

3.编辑器的实例化页面,导入编辑器需要的三个入口文件,示例代码如下:

<!-- 配置文件 -->
<script type="text/javascript" src="${contextPath}/styles/ueditor/ueditor.config.js"></script>
<!-- 编辑器源码文件 -->
<script type="text/javascript" src="${contextPath}/styles/ueditor/ueditor.all.js"></script>
<!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
<script type="text/javascript" charset="utf-8" src="${contextPath}/styles/ueditor/lang/zh-cn/zh-cn.js"></script>


4.然后在编辑器的实例化页面中创建编辑器实例及其DOM容器,示例代码如下:

html:

<textarea id="projectBasis" class="editor" name="projectBasis" cols="150" rows="30" maxlength="8000" style="width: 130%"> </textarea>


javascript:

<!-- 实例化编辑器 -->
<script type="text/javascript">
var URL = getRootPath();

var ue = UE.getEditor('projectBasis', {
//为编辑器实例添加一个路径,这个不能被注释
UEDITOR_HOME_URL: URL + '/styles/ueditor/',
// 服务器统一请求接口路径
serverUrl: '<%=basePath%>/styles/ueditor/jsp/controller.jsp',
//这里可以选择自己需要的工具按钮名称
toolbars:[[
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'Undo', 'Redo','Bold','test', 'simpleupload', 'insertimage','|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow'
]],
//focus时自动清空初始化时的内容
autoClearinitialprojectBasis:true,
//关闭字数统计
//wordCount:false,
maximumWords:8000,       //允许的最大字符数
//关闭elementPath 元素路径
elementPathEnabled:false,
//默认的编辑区域高度
initialFrameHeight:300,
initialFrameWidth:1000  //初始化编辑器宽度,默认1000
});

//自定义请求地址

UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
if (action == 'uploadimage' || action == 'uploadimage') {
return '<%=basePath%>/management/project/projectApplication/upload/img';
} else {
return this._bkGetActionUrl.call(this, action);
}
}

/**
* js获取项目根路径,如: http://localhost:8083/project */
function getRootPath(){
//获取当前网址,如: http://localhost:8083/project/share/meun.jsp var curWwwPath=window.document.location.href;

//获取主机地址之后的目录,如: project/share/meun.jsp
var pathName=window.document.location.pathname;

var pos=curWwwPath.indexOf(pathName);

//获取主机地址,如: http://localhost:8083 var localhostPaht=curWwwPath.substring(0,pos);

//获取带"/"的项目名,如:/project
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);

//return localhostPaht + projectName;
return localhostPaht + projectName;
}

</script>


项目放置如图所示:



需要的jar包:



ueditor/jsp/controller.jsp做一下修改,以便【在线管理】功能才能显示图片处理。



在实例化是已经自定义
[align=left] //为编辑器实例添加一个路径,这个不能被注释[/align]
      // UEDITOR_HOME_URL:
URL
[align=left]       // 服务器统一请求接口路径[/align]

       //, serverUrl: URL + "jsp/controller.jsp"
所以这边要注释掉。



然后就到后台action了:

  
/**
*   图片上传
* @author CK
* @param upfile
* @param request
* @param response
* @return
* @throws Exception
*
*/
@RequestMapping("/upload/img")
@ResponseBody
public String upload(@RequestParam("upfile") MultipartFile upfile,HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String result = null;
String originalName = upfile.getOriginalFilename();//返回客户端文件的原始名称,eg:atv1.png

String imgFileSuffix = "";//图像文件的后缀
String mimeType = upfile.getContentType();
String supportedFormatTable[][] = {
{"image/png", ".png"},
{"image/bmp", ".bmp"},
{"image/jpg", ".jpg"},
{"image/gif", ".gif"},
{"image/jpeg", ".jpg"}
};

for (int i = 0; i < supportedFormatTable.length; ++i) {
if (supportedFormatTable[i][0].equals(mimeType)) {
imgFileSuffix = supportedFormatTable[i][1];
break;
}
}

//文件的前缀,eg:201503271453000025
String imgFilePrefix = new SimpleDateFormat("yyyyMMddHHmmssssss").format(Calendar.getInstance().getTime());
String newImgFileName = imgFilePrefix + imgFileSuffix;

String uploadPath = request.getSession().getServletContext().getRealPath("upload") + "/image";

// 拼装uuid
String uuid = "img_" + imgFilePrefix;

//删除已存在的文件
File uploadedFile1 = new File(uploadPath, newImgFileName);

if (uploadedFile1.exists()) {
uploadedFile1.delete();
}

//保存到数据库以及保存到相应的目录文件里
Resource oldResource = resourceService.get(uuid);

if (oldResource != null) {
File uploadedFile = new File(uploadPath, newImgFileName);
org.apache.commons.io.FileUtils.writeByteArrayToFile(uploadedFile, upfile.getBytes());
oldResource.setName(upfile.getOriginalFilename());
oldResource.setFileSize(FileUtils.getHumanReadableFileSize(upfile.getSize()));
oldResource.setUploadTime(new Date());
oldResource.setUuid(uuid);
oldResource.setStoreType(StoreType.IMAGE);
resourceService.update(oldResource);
} else {
File uploadedFile = new File(uploadPath, newImgFileName);
org.apache.commons.io.FileUtils.writeByteArrayToFile(uploadedFile, upfile.getBytes());
Resource resource = new Resource();
resource.setName(newImgFileName);
resource.setFileSize(FileUtils.getHumanReadableFileSize(upfile.getSize()));
resource.setUploadTime(new Date());
resource.setUuid(uuid);
resource.setStoreType(StoreType.IMAGE);
resourceService.save(resource);
}

String projectUrl = "http://" + request.getServerName() //服务器地址
+ ":"
+ request.getServerPort()           //端口号
+ request.getContextPath();      //项目名称

//{"name":"10571402926855858.jpg", "originalName": "china.jpg", "size": 43086, "state": "SUCCESS", "type": ".jpg", "url": "upload/20140616/10571402926855858.jpg"}
// result返回的url参照IndexController._file方法

result = "{\"name\":\""+ newImgFileName +"\", \"originalName\": \""+ originalName +"\", \"size\": "+ upfile.getSize() +", \"state\": \"SUCCESS\", \"type\": \""+FileUtils.getFileExt(originalName)+"\", \"url\": \"" + projectUrl + "/upload/image/" + newImgFileName +"\"}";
result = result.replaceAll( "\\\\", "\\\\" );
return result;
}


需要返回的格式:

{
"name": "201608171525000017.png",
"originalName": "check-radio.png",
"size": 4572,
"state": "SUCCESS",
"type": "png",
"url": "http://localhost:8080/project/upload/image/201608171525000017.png"
}








结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息