Ckeditor结合springmvc的使用、配置、上传图片、分页

项目中管理员用户需要用到ckeditor,对着文档研究了几天,本人用的是3.5.3,

1使用

首先需要下载ckeditor压缩包,解压后导入项目中,

引包,项目中用到maven,只需要在pom.xml配置

<dependency>
<groupId>com.ckeditor</groupId>
<artifactId>ckeditor-java-core</artifactId>
<version>3.5.3</version>
</dependency>

项目中如果没有用到maven,则需要引三个包ckeditor-java-core-3.5.3   ckeditor-java-core-3.5.3-javadoc   ckeditor-java-core-3.5.3-javadoc

如果对ckeditor课去官网下载源码,如果觉得麻烦可去本人博客下载

<form method="post" action="">
<p>
My Editor:
<br />
<textarea id="editor1" name="editor1"></textarea>
<script type="text/javascript">
CKEDITOR.replace('editor1', 
{
customConfig : 'basepath/ckeditor/config.js'


});
</script>
</p>
<p>
<input type="submit" />
</p>
</form>

详见官方文档,路径为config.js的路径

2配置文件config.js

可以修改各种配置,详见官方文档或者网上搜索

CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
config.uiColor = '#1106';


 
 config.toolbar = 'MyToolbar';//把默认工具栏改为‘MyToolbar’ 


    config.toolbar_MyToolbar = 
    [ 
        [ 'Source','-','Save','Preview','Print' ] ,
        [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ], 
        [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ], 
         [ 'Link','Unlink','Anchor' ] ,
        ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
         ['Maximize','-','About'] ,
        '/', 
       ['Font','FontSize' ], 
       [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ],
       [ 'TextColor','BGColor' ] ,
        ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'], 
        [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv',
'-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ]
       
    ]; 
// 换行方式
 config.enterMode = CKEDITOR.ENTER_BR;
 // 当输入:shift+Enter是插入的标签
 config.shiftEnterMode = CKEDITOR.ENTER_BR;

config.font_names = '微软雅黑;宋体;新宋体;黑体;隶书;幼圆;楷体_GB2312;仿宋_GB2312;方正舒体;方正姚体;华文隶书;华文新魏;华文行楷;sans-serif;Arial;Comic Sans MS;Courier New;Tahoma';
};

3图片上传

项目中用的是springmvc,网上搜到一大堆资料,但是springmvc上传文件,图片类型要用特殊数据格式传输

修改配置文件

    // 图片浏览配置  

    config.width = 500; //宽度
        config.height = 300; //高度
     
   config.filebrowserImageUploadUrl = 'ckeditor/upload?MultipartFile[]=upload';

     config.filebrowserFlashUploadUrl = 'ckeditor/upload?MultipartFile[]=upload';

注意参数,MultipartFile[]=upload,MultipartFile是springmvc用于接收文件类型的,upload是ckeditor上传文件表单的命名


上传图片代码:

@Controller
 @RequestMapping("/ckeditor")
public class CkeditorUpLoad {  
@RequestMapping("/upload")

public void addVideo(HttpServletResponse response,
HttpServletRequest request, HttpSession session,
@RequestParam MultipartFile[] upload) {

Map<String, Object> m = new HashMap<String, Object>();
response.setCharacterEncoding("utf-8");
m.put("error", 1);
m.put("message", "上传成功!");
// 文件保存目录路径
String savePath = session.getServletContext().getRealPath("/")
+ "attached/";


// 文件保存目录URL
String saveUrl = request.getContextPath() + "/attached/";


// 定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", ConfigUtil.get("image"));
extMap.put("flash", ConfigUtil.get("flash"));
extMap.put("media", ConfigUtil.get("media"));
extMap.put("file", ConfigUtil.get("file"));
long maxSize = Long.parseLong(ConfigUtil.get("maxFileSize")); // 允许上传最大文件大小(字节)


if (!ServletFileUpload.isMultipartContent(request)) {
m.put("error", 1);
m.put("message", "请选择文件!!!");
// return m;
}


// 检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
uploadDir.mkdirs();
}


// 检查目录写权限
if (!uploadDir.canWrite()) {
m.put("error", 1);
m.put("message", "上传目录没有写权限!");
// return m;
}


String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if (!extMap.containsKey(dirName)) {
m.put("error", 1);
m.put("message", "目录名不正确!");
// return m;
}


// 创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
// 路径1
// System.out.println("saveUrl1:"+saveUrl);
// saveUrl1:/ssim/attached/image/
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDf = new SimpleDateFormat("MM");
SimpleDateFormat dateDf = new SimpleDateFormat("dd");
Date date = new Date();
String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/"
+ dateDf.format(date) + "/";
savePath += ymd;
saveUrl += ymd;
// 路径2
// System.out.println("saveUrl2"+saveUrl);
// saveUrl2/ssim/attached/image/2014/04/12/
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
try {
for (MultipartFile myfile : upload) {
String Name = myfile.getOriginalFilename();
System.out.println("Name:" + Name);
String fileName = myfile.getName();
System.out.println("fileName:" + fileName);
if (myfile.isEmpty()) {
System.out.println("文件为空!");
} else {
if (myfile.getSize() > maxSize) {
m.put("error", 1);
m.put("message", "上传文件大小超过限制!(允许最大[" + maxSize
+ "]字节,您上传了[" + myfile.getSize() + "]字节)");
// return m;
}
// 检查扩展名
String fileExt = Name.substring(
Name.lastIndexOf(".") + 1,Name.length()).toLowerCase();

System.out.println("fileExt:" + fileExt);
if (!Arrays.<String> asList(extMap.get(dirName).split(","))
.contains(fileExt)) {
m.put("error", 1);
m.put("message", "上传文件扩展名是不允许的扩展名。\n只允许"
+ extMap.get(dirName) + "格式!");
// return m;
}



String newFileName = UUID.randomUUID().toString() + "."
+ fileExt;
String originalFilename = myfile.getOriginalFilename();
// 生成的图片文件名
// newFileName:8f99ab42-bfa1-4592-a98e-cda9e7bf9932.jpg
System.out.println("newFileName:" + newFileName);
try {
File uploadedFile = new File(savePath, newFileName);


System.out.println("savaPath+newFileName:" + savePath
+ newFileName);
// myfile.write(uploadedFile);
// 此处也可以使用Spring提供的MultipartFile.transferTo(File
// dest)方法实现文件的上传
FileUtils.copyInputStreamToFile(
myfile.getInputStream(), new File(savePath,
newFileName));
} catch (Exception e) {
m.put("error", 1);
m.put("message", "上传文件失败!");
// return m;
}
String callback =request.getParameter("CKEditorFuncNum"); 

PrintWriter out=response.getWriter();
out.println("<script type='text/javascript'>");
out.println("window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" +saveUrl+ newFileName  + "',''" + ")");
out.println("</script>");
m.put("error", 0);
// saveUrl+newFileName即保存到数据的路径
m.put("url", saveUrl + newFileName);
}
}
} catch (Exception e) {
e.printStackTrace();
}



}

4分页

网上搜到一大堆分页的,都说由于浏览器不同的原因要用js解析,但是大部分代码都少了两个分号,(下面代码红色部分)用在线编辑器的时候,点击源码会发现,分页代码是这样子的:

<div style="page-break-after: always;">
<span style="display: none;">&nbsp;</span></div>

但是网上很多代码都漏掉了always和none后面的分号

正确方法:

String content = request.getParameter("editor1");
//需要用正則表達式解析
String patternStr = "(?is)<div style=\"page-break-after: always;\">(.*?)<span style=\"display: none;\">&nbsp;</span></div>"; 
Pattern p= Pattern.compile(patternStr); 
Matcher m=p.matcher(content);
content=m.replaceAll("<div style=\"page-break-after: always;\"><span style=\"display: none;\">&nbsp;</span></div>"); 
//对内容进行分页
String pattern = "<div style=\"page-break-after: always;\"><span style=\"display: none;\">&nbsp;</span></div>"; 
String[] contentSplit = content.split(pattern);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值