SSM框架+kindeditor实现文件上传和图片回显

富文本编辑器为客户资料编辑带来很大遍历,很多新同学却不能实现其内带的文件上传,不能发挥其最大功能。这里使用SSM框架结合kindeditor实现其文件上传和图片回显功能。
SSM框架(版本不重要)
KindEditor 4.1.11 目前最新版本

  1. 目录结构如下
    SSM框架+kindeditor实现文件上传和图片回显
  2. index.jsp就是测试页面,引入KindEditor要先引入jquery(主要引入2.x版本即可,太高不支持)
<script src="${pageContext.servletContext.contextPath}/js/jquery.min.js"
	type="text/javascript"></script>
<link rel="stylesheet"
	href="${pageContext.servletContext.contextPath}/js/editor/themes/default/default.css" />
<script charset="utf-8"
	src="${pageContext.servletContext.contextPath}/js/editor/kindeditor-all-min.js"></script>
<script charset="utf-8"
	src="${pageContext.servletContext.contextPath}/js/editor/lang/zh-CN.js"></script>
  1. 定义编辑器配置参数
var options={
				allowFileManager:true,
				uploadJson:'${pageContext.servletContext.contextPath}/upload.action',
				filePostName:'file',
				afterUpload:function(data){
					/*上传完成后要做的事情*/
				},
				urlType:'absolute'
		};
		/*
		uploadJson:请求的controller地址
		filePostName:上传文件的参数名,congtroller接收参数名字为这个
		afterUpload:上传完成后回调方法,例如存起来等,没处理就不写
		urlType:回显路径绝对值,我这里映射了站外路径,
		*/
  1. 创建富文本编辑器对象
	  KindEditor.ready(function(K) {
			window.editor = K.create('#editor_id',options);			
		});
		/*#editor_id要替换成富文本编辑器的组件id*/
  1. 页面内富文本编辑器显示的位置
<textarea id="editor_id" name="content"		style="width: 700px; height: 300px;">
</textarea>
  1. controller里上传方法(editor要求上传返回的结果为map的json格式)
//上传的文件目录通过配置文件获得
	@Value("${file_baseFile}")
	private String baseFile;
//回显路径也通过配置文件
	@Value("${file_imgBaseURL}")
	private String imgBaseURL;
	@RequestMapping("/upload")
	@ResponseBody
	public Map uploadFile(MultipartFile file) {
		String oldName = file.getOriginalFilename();
		logger.debug("文件上传..."+oldName);
		HashMap map = new HashMap();
		String newName=UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."));
		try {
			file.transferTo(new File(baseFile, newName));
			map.put("error", 0);
			map.put("url",imgBaseURL+newName);
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			map.put("error", 1);
			map.put("message", "文件上传失败,请稍后重新尝试!");
		}		
		return map;
	}
  1. 然后富文本编辑器里的上传就都可以使用了,并且可以回显
    SSM框架+kindeditor实现文件上传和图片回显
    SSM框架+kindeditor实现文件上传和图片回显

同志们,可以试试了
Created by 薛萌
SSM框架+kindeditor实现文件上传和图片回显