kindeditor的简单使用
上传到云:
一、引入kindeditor
<%@ page language="java" contentType="text/html; charset=UTF-8"%> <%@ include file="/WEB-INF/views/commons/taglibs.jsp"%> <html> <head> <script type="text/javascript"> yepnope({ load:[ '${ctx}/resources/kindeditor/themes/default/default.css', '${ctx}/resources/kindeditor/plugins/code/prettify.css', '${ctx}/resources/js/ux/KindEditor.js', '${ctx}/resources/kindeditor/kindeditor.js', '${ctx}/resources/kindeditor/lang/zh_CN.js', '${ctx}/resources/kindeditor/plugins/code/prettify.js', '${ctx}/resources/extjs/ux/combotree/ComboTree.js', '${ctx}/resources/extjs/ux/css/Spinner.css', '${ctx}/resources/extjs/ux/Spinner.js', '${ctx}/resources/extjs/ux/SpinnerField.js', '${ctx}/resources/extjs/ux/DateTimeField.js', '${ctx}/plugins/websites/web/resources/js/news/NewsFormPanel.js', '${ctx}/plugins/websites/web/resources/js/news/NewsFormWin.js', '${ctx}/plugins/websites/web/resources/js/news/NewsReadWindow.js', '${ctx}/plugins/websites/web/resources/js/news/NewsUploadWindow.js', '${ctx}/plugins/websites/web/resources/js/news/NewsPanel.js', '${ctx}/plugins/websites/web/resources/js/news/NewsSynFormWin.js', '${ctx}/plugins/websites/web/resources/js/news/NewsSynFormPanel.js', '${ctx}/plugins/websites/web/resources/js/news/ImportNewsWin.js', '${ctx}/plugins/websites/web/resources/js/news/TreeWindow.js', '${ctx}/resources/js/shareux.js', '${ctx}/resources/js/ux/StarHtmleditor.js'], complete:function(){ var panel = new Ext.websites.NewsPanel({ height : index.tabPanel.getInnerHeight() - 1, id: '${param.id}' + '_panel', actionJson:${actionJson}, renderTo: '${param.id}' }); } }); </script> </head> <body> <div id="${param.id}"></div> </body> </html>
二、重写下kindeditor方法
Ext.ux.KindEditor = Ext.extend(Ext.form.TextArea, { uploadUrl:null, render : function(editor) { Ext.ux.KindEditor.superclass.render.call(this, editor); var contentId = this.id; if(this.uploadUrl == undefined){ this.uploadUrl = 'kindEditor/upload'; } var that = this; window.setTimeout(function() { that.myEditor = KindEditor.create('#' + contentId, { cssPath : 'resources/kindeditor/plugins/code/prettify.css', uploadJson : that.uploadUrl, // uploadJson:'resources/kindeditor/jsp/upload_json.jsp', fileManagerJson : 'resources/kindeditor/jsp/file_manager_json.jsp', resizeType : 1, resizeMode : 1, filterMode : false, allowFileManager : true, afterCreate : function(id) { /* 响应 ctrl + v ,保存图片* */ //KindEditor.ctrl(document, 'v', function() { // }); // KindEditor.ctrl(KindEditor.g[id].iframeDoc, 86, function() { // KindEditor.util.setData(id); // var doc = KindEditor.g[id].iframeDoc; // setTimeout(dealdoc(doc), 100); // }); // // ie 中粘贴 --- 包括 toolbar 中 的粘贴和右键浏览器菜单中的粘贴 // KindEditor.g[id].iframeDoc.body.onpaste = function() { // var doc = KindEditor.g[id].iframeDoc; // setTimeout(dealdoc(doc), 100); // }; // // firefox 粘贴 --- 包括 ctrl+v 和右键浏览器菜单中的粘贴 // $(KindEditor.g[id].iframeDoc).bind('paste', null, function() { // var doc = KindEditor.g[id].iframeDoc; // setTimeout(dealdoc(doc), 100); // }); } }); }, 500); }, getValue : function() { if (this.myEditor) { return this.myEditor.html(); } else { return ''; } }, setValue : function(v) { var contentId = this.id; var that = this; window.setTimeout(function() { KindEditor.html('#' + contentId, v); }, 500); } }); // 返回 一个无参的方法,用于setTimeout function dealdoc(doc) { return function() { deal(doc); } } // 粘贴时处理图片-- 方法二:同步,可以接受多张图片 function deal(doc) { var links = doc.getElementsByTagName("img"); for (var i = 0; i < links.length; i++) { var lin = $(links[i]); if ($(lin).attr("add_src")) { } else { // links[i].src = "<c:url // value='/saveImageServlet?mageurl='/>"+links[i].src; var imgurl = $(lin).attr("src"); var html = $.ajax({ type : "POST", url : "<c:url value='/saveImageServlet'/>", data : "imageurl=" + imgurl, dataType : "html", async : false }).responseText; $(lin).attr("src", ""); $(lin).attr("src", html); $(lin).attr("add_src", "1"); } } } Ext.reg('kindeditor', Ext.ux.KindEditor);
这个是上面引入的ux包下的kindeditor方法
三、kindeditor上传的controller
package cn.edu.hbcf.privilege.web.controller; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.json.simple.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import cn.edu.hbcf.common.hadoop.FileManager; import cn.edu.hbcf.common.hadoop.FileSysFactory; import cn.edu.hbcf.common.hadoop.FileSysType; @Controller @RequestMapping("/kindEditor") public class KindeditorController { @RequestMapping("/upload") public void upload(@RequestParam MultipartFile imgFile, HttpServletRequest request, String dir, HttpServletResponse response) { try { // 定义允许上传的文件扩展名 response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); Map<String, String> extMap = new HashMap<String, String>(); extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("flash", "swf,flv"); extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); String fileName = imgFile.getOriginalFilename(); // 检查扩展名 String fileExt = StringUtils.substringAfterLast(fileName, ".").toLowerCase(); if (!Arrays.<String> asList(extMap.get(dir).split(",")).contains( fileExt)) { out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dir) + "格式。")); return; } // 获取文件后缀名 String saveName = UUID.randomUUID().toString().replace("-", "")+("".equals(fileExt) ? "" : "." + fileExt); String filePath="/filesharesystem/attach"; FileManager fileMgr=FileSysFactory.getInstance(FileSysType.HDFS); fileMgr.putFile(imgFile.getInputStream(), filePath, saveName); // JSONObject obj = new JSONObject(); obj.put("error", 0); if("image".equals(dir)||"media".equals(dir)||"flash".equals(dir)){ obj.put("url", "dfs/queryResource?resourcePath="+filePath+"/"+saveName); }else{ obj.put("url", "dfs/downloadFile?filePath="+filePath+"/"+saveName+"&fileName="+fileName); } System.out.println("AAAAAAAAAURL:"+obj.get("url")); out.println(obj.toJSONString()); } catch (Exception e) { e.printStackTrace(); } } private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString(); } }
四、根据地址预览、下载文件的方法
package cn.edu.hbcf.cloud.hadoop.dfs.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import cn.edu.hbcf.cloud.hadoop.dfs.service.DFSService; import cn.edu.hbcf.cloud.hadoop.dfs.vo.DfsInfo; import cn.edu.hbcf.common.constants.WebConstants; import cn.edu.hbcf.common.hadoop.CFile; import cn.edu.hbcf.common.hadoop.FileManager; import cn.edu.hbcf.common.hadoop.FileSysFactory; import cn.edu.hbcf.common.hadoop.FileSysType; import cn.edu.hbcf.common.vo.Criteria; import cn.edu.hbcf.common.vo.ExceptionReturn; import cn.edu.hbcf.common.vo.ExtFormReturn; import cn.edu.hbcf.plugin.oa.pojo.NoteBook; import cn.edu.hbcf.privilege.pojo.BaseUsers; @Controller @RequestMapping("/dfs") public class DFSController { @Autowired private DFSService dfsService; @RequestMapping(method=RequestMethod.GET) public String index(HttpServletRequest request,HttpSession session,Model model){ return "plugins/cloud/web/views/hadoop/dfs/dfs"; } @RequestMapping(value = "/play",method=RequestMethod.GET) public String play(HttpServletRequest request,HttpSession session,Model model){ return "plugins/cloud/web/views/hadoop/dfs/play"; } @RequestMapping("/upload") public void upload(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response){ String uploadFileName = file.getOriginalFilename(); FileManager fileMgr=FileSysFactory.getInstance(FileSysType.HDFS); String path=request.getParameter("path"); HttpSession session=request.getSession(true); BaseUsers u = (BaseUsers) session.getAttribute(WebConstants.CURRENT_USER); // 获取文件后缀名 String fileType = StringUtils.substringAfterLast(uploadFileName, "."); String saveName = UUID.randomUUID().toString().replace("-", "")+("".equals(fileType) ? "" : "." + fileType); String filePath="/filesharesystem/"+u.getAccount()+path; try { fileMgr.putFile(file.getInputStream(), filePath, saveName); System.out.println("path="+filePath+" uploadFileName="+uploadFileName); StringBuffer buffer = new StringBuffer(); buffer.append("{success:true,fileInfo:{fileName:'").append(uploadFileName).append("',"); buffer.append("filePath:'").append(filePath+saveName).append("',"); buffer.append("projectPath:'").append(filePath+saveName).append("',"); buffer.append("storeName:'").append(saveName); buffer.append("'}}"); response.setContentType("text/html;charset=utf-8;"); response.getWriter().write(buffer.toString()); response.getWriter().flush(); response.getWriter().close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @RequestMapping(value="/downloadFile", method = RequestMethod.GET) public void download(HttpServletRequest request, HttpServletResponse response,String filePath,String fileName) { //String fileName=request.getParameter("fileName"); try { fileName=new String(fileName.getBytes("ISO-8859-1"),"UTF-8"); filePath=new String(filePath.getBytes("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } OutputStream output = null; BufferedInputStream bis=null; BufferedOutputStream bos=null; FileManager fileMgr=FileSysFactory.getInstance(FileSysType.HDFS); //response.setContentType("application/x-msdownload"); //response.setCharacterEncoding("UTF-8"); try { output = response.getOutputStream(); response.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("gbk"),"iso-8859-1")); bis=new BufferedInputStream(fileMgr.getFile(filePath)); bos=new BufferedOutputStream(output); byte[] buff=new byte[2048]; int bytesRead; while(-1!=(bytesRead=bis.read(buff,0,buff.length))){ bos.write(buff,0,bytesRead); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if(bis!=null) try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(bos!=null) try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @RequestMapping("/delete") public void delete(String path, HttpServletResponse response){ FileManager fileMgr=FileSysFactory.getInstance(FileSysType.HDFS); try { fileMgr.deleteFile(path); StringBuffer buffer = new StringBuffer(); buffer.append("{success:true}"); response.setContentType("text/html;charset=utf-8;"); response.getWriter().write(buffer.toString()); response.getWriter().flush(); response.getWriter().close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @RequestMapping(value ="/queryMovie",method=RequestMethod.GET) public void queryMovie( HttpServletRequest request, HttpServletResponse response){ response.setContentType("application/octet-stream"); FileManager fileMgr = FileSysFactory.getInstance(FileSysType.HDFS); FSDataInputStream fsInput = fileMgr.getStreamFile("/filesharesystem/admin/test/a.swf"); OutputStream os; try { os = response.getOutputStream(); IOUtils.copyBytes(fsInput, os, 4090, false); os.flush(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 根据提交的路径,从云上获取swf格式和picture文档内容 */ @RequestMapping(value = "/queryResource", method = RequestMethod.GET) public void queryResource(HttpServletRequest request, HttpServletResponse response, String resourcePath) { response.setContentType("application/octet-stream"); FileManager fileMgr = FileSysFactory.getInstance(FileSysType.HDFS); FSDataInputStream fsInput = fileMgr.getStreamFile(resourcePath); OutputStream os = null; try { os = response.getOutputStream(); IOUtils.copyBytes(fsInput, os, 4090, false); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { if(os != null){ os.flush(); os.close(); } if(fsInput!= null){ fsInput.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @RequestMapping(value = "/queryListForTree", method = RequestMethod.POST) @ResponseBody public List<CFile> queryListForTree(HttpServletRequest request) { HttpSession session=request.getSession(true); BaseUsers u = (BaseUsers) session.getAttribute(WebConstants.CURRENT_USER); Criteria criteria = new Criteria(); criteria.put("username", u.getAccount()); return dfsService.queryListForTree(criteria); } @RequestMapping(value="/status",method=RequestMethod.GET) public String dfsIndex(HttpServletRequest request,HttpSession session,Model model){ return "plugins/cloud/web/views/hadoop/dfs/dfsStatus"; } @RequestMapping(value="/status", method = RequestMethod.POST) @ResponseBody public Object get(HttpSession session){ try{ DfsInfo dfs = dfsService.getDfsInfo(); if(dfs != null){ return new ExtFormReturn(true,dfs); }else{ return new ExtFormReturn(false); } }catch(Exception e){ e.printStackTrace(); return new ExceptionReturn(e); } } @RequestMapping(value="/dataNode", method = RequestMethod.POST) @ResponseBody public Object dataNode(){ try{ return dfsService.getDataNodeList(); }catch(Exception e){ e.printStackTrace(); return new ExceptionReturn(e); } } }
即可。
上传到本地服务器:
/** * 描述:公司网站内容kindeditor上传图片 * @param imgFile * @param request * @param dir * @param response */ @RequestMapping("/uploadKindEditor") public void upload(@RequestParam MultipartFile imgFile, HttpServletRequest request, String dir, HttpServletResponse response) { try { response.setContentType("text/html;charset=utf-8;"); PrintWriter out = response.getWriter(); Map<String, String> extMap = new HashMap<String, String>(); extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("flash", "swf,flv"); extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); // 检查扩展名 String fileName = imgFile.getOriginalFilename(); String fileExt = StringUtils.substringAfterLast(fileName, ".").toLowerCase(); if (!Arrays.<String> asList(extMap.get(dir).split(",")).contains( fileExt)) { out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dir) + "格式。")); return; } // 保存的地址 String savePath = request.getSession().getServletContext().getRealPath("/"+"/upload/web"); // 上传的文件名 //需要保存 String uploadFileName = imgFile.getOriginalFilename(); // 获取文件后缀名 //需要保存 String fileType = StringUtils.substringAfterLast(uploadFileName, "."); // 以年月/天的格式来存放 String dataPath = DateFormatUtils.format(new Date(), "yyyy-MM" + File.separator + "dd"); // uuid来保存不会重复 String saveName = UUID.randomUUID().toString().replace("-", ""); // 最终相对于upload的路径,解决没有后缀名的文件 //需要保存 // 为了安全,不要加入后缀名 // \2011-12\01\8364b45f-244d-41b6-bbf4-8df32064a935,等下载的的时候在加入后缀名 String finalPath = File.separator + dataPath + File.separator + saveName + ("".equals(fileType) ? "" : "." + fileType); // String filePath = savePath.replace("\\", "/")+finalPath.replace("\\", "/"); File saveFile = new File(savePath + finalPath); // 判断文件夹是否存在,不存在则创建 if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } // 写入文件 FileUtils.writeByteArrayToFile(saveFile, imgFile.getBytes()); // 保存文件的基本信息到数据库 //图片相对tomcat路径 String imgPath = "/upload/web".replace("\\", "/") + finalPath.replace("\\", "/"); JSONObject obj = new JSONObject(); obj.put("error", 0); if("image".equals(dir)){ obj.put("url", "web/queryResource?resourcePath="+imgPath); // obj.put("url", "web/queryResource?resourcePath="+filePath+"/"+saveName); }else{ // obj.put("url", "dfs/downloadFile?filePath="+filePath+"/"+saveName+"&fileName="+fileName); out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dir) + "格式。")); return; } System.out.println("AAAAAAAAAURL:"+obj.get("url")); out.println(obj.toJSONString()); } catch (Exception e) { e.printStackTrace(); } } @RequestMapping(value = "/queryResource", method = RequestMethod.GET) public void queryResource(HttpServletRequest request, HttpServletResponse response, String resourcePath) { response.setContentType("application/octet-stream"); // FileManager fileMgr = FileSysFactory.getInstance(FileSysType.HDFS); // FSDataInputStream fsInput = fileMgr.getStreamFile(resourcePath); String path = request.getSession().getServletContext().getRealPath("/"); File file = new File(path+resourcePath); InputStream in = null; OutputStream os = null; try { in = new FileInputStream(file); os = response.getOutputStream(); IOUtils.copy(in, os); } catch (IOException e) { e.printStackTrace(); } finally{ try { if(os != null){ os.flush(); os.close(); } if(in != null){ in.close(); } } catch (IOException e) { e.printStackTrace(); } } } private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString(); }
<%@ page language="java" contentType="text/html; charset=UTF-8"%><%@ include file="/WEB-INF/views/commons/taglibs.jsp"%><html><head><script type="text/javascript">yepnope({load:['${ctx}/resources/kindeditor/themes/default/default.css','${ctx}/resources/kindeditor/plugins/code/prettify.css','${ctx}/resources/js/ux/KindEditor.js','${ctx}/resources/kindeditor/kindeditor.js','${ctx}/resources/kindeditor/lang/zh_CN.js','${ctx}/resources/kindeditor/plugins/code/prettify.js','${ctx}/resources/extjs/ux/combotree/ComboTree.js','${ctx}/resources/extjs/ux/css/Spinner.css','${ctx}/resources/extjs/ux/Spinner.js','${ctx}/resources/extjs/ux/SpinnerField.js','${ctx}/resources/extjs/ux/DateTimeField.js','${ctx}/plugins/websites/web/resources/js/news/NewsFormPanel.js','${ctx}/plugins/websites/web/resources/js/news/NewsFormWin.js','${ctx}/plugins/websites/web/resources/js/news/NewsReadWindow.js','${ctx}/plugins/websites/web/resources/js/news/NewsUploadWindow.js','${ctx}/plugins/websites/web/resources/js/news/NewsPanel.js','${ctx}/plugins/websites/web/resources/js/news/NewsSynFormWin.js','${ctx}/plugins/websites/web/resources/js/news/NewsSynFormPanel.js','${ctx}/plugins/websites/web/resources/js/news/ImportNewsWin.js','${ctx}/plugins/websites/web/resources/js/news/TreeWindow.js','${ctx}/resources/js/shareux.js', '${ctx}/resources/js/ux/StarHtmleditor.js'],complete:function(){var panel = new Ext.websites.NewsPanel({height : index.tabPanel.getInnerHeight() - 1, id: '${param.id}' + '_panel', actionJson:${actionJson}, renderTo: '${param.id}'});}});</script></head><body><div id="${param.id}"></div></body></html>