富文字編輯ckeditor.js的使用
阿新 • • 發佈:2018-11-08
使用ckeditor.js編輯副本,生成靜態頁面
前端程式碼:
<div style="margin:20px"> <textarea rows="20" name="editor" id="editor"></textarea><br/> <a onclick="submit()" class="btn btn-default disabled float-right" style="display: block;">上傳</a> </div> <script type="text/javascript"> $(function() { var editor = CKEDITOR.replace('editor'); submit = function() { if (!editor.getData()) { return; } $.ajax({ url:"uploadHtml", type:"POST", data:{html : editor.getData()}, dataType:'json', //返回的資料格式:json/xml/html/script/jsonp/text success:function(data){ Alert(data.flag); }, error:function(data){ } }); } } }); </script>
注:使用editor.getData()獲得富文字中的內容,圖片可以使用複製貼上放入文字框
後臺java程式碼:
@RequestMapping("uploadHtml") public @ResponseBody Map<String,Object> uploadHtml(String html, HttpServletRequest request) { StringBuilder stringHtml = new StringBuilder(); try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } //輸入HTML檔案內容 stringHtml.append("<html><head>"); stringHtml.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); stringHtml.append("<title>測試報告文件</title>"); stringHtml.append("</head>"); stringHtml.append("<body>"); stringHtml.append("<div>hello</div>"); stringHtml.append("</body></html>"); String sb = null; if (Common.isEmpty(html)) { StringBuffer sbuffer=new StringBuffer(); try { BufferedReader br=request.getReader(); char[] buffer=new char[1024*1024]; int len; while((len=br.read(buffer))!=-1) { sbuffer.append(buffer,0,len); } sb = URLDecoder.decode(String.valueOf(sbuffer), "utf-8"); sb = String.valueOf(stringHtml).replace("hello", sb.split("html=")[1].replace("<img", "<img style=\"width:80%;height:auto\"")); } catch (Exception e) { e.printStackTrace(); } } else { sb = String.valueOf(stringHtml).replace("hello", html.replace("<img", "<img style=\"width:80%;height:auto\"")); } if (Common.isEmpty(sb)) { throw new IllegalArgumentException(); } Map<String,Object> hm = new HashMap<String,Object>(); try { File detail = new File("C:/uploadDoc/detail.html"); FileOutputStream fos = new FileOutputStream (detail); OutputStreamWriter bw = new OutputStreamWriter(fos, "UTF-8"); bw.write(sb); bw.close(); hm.put("flag", "SUCCESS:文件上傳成功"); } catch (Exception e) { e.printStackTrace(); hm.put("flag", "ERROR:文件上傳失敗"); } return hm; }
使用request.getReader()獲取超過上傳要求的位元組數