天天看點

ckeditor結合SpringMVC的使用

1.在官網上下載下傳CKeditor包,進行解壓,将解壓後的檔案夾放到項目webcontent目錄下

ckeditor結合SpringMVC的使用

2.在需要用到ckeditor的頁面導入ckeditor.js

<script src="${pageContext.request.contextPath}/static/js/My97DatePicker/WdatePicker.js" type="text/javascript" ></script>

ckeditor結合SpringMVC的使用

 在使用編輯器的地方加上如下代碼:

ckeditor結合SpringMVC的使用

<textarea id="contentEditor" name="contentEditor" cols="20" rows="2" class="ckeditor"></textarea>

<script type="text/javascript">

//執行個體化編輯器

CKEDITOR.replace('contentEditor',  { 

//清空預覽區域顯示内容

   image_previewText : '',

   //圖檔上傳

   filebrowserUploadUrl : '<%=request.getContextPath()%>/policyController/imageUpload.do',

} );

</script>

3、ckeditor編輯器上傳圖檔

點選上傳到伺服器:指定上傳圖檔路徑,有兩種方式,一種是在config.js中指定,另一種是在執行個體化編輯器的時候指定圖檔上傳路徑,通過filebrowerUploadUrl屬性指定,如上圖,後面為SpringMvc上傳路徑。

背景上傳代碼:

 @ResponseBody

@RequestMapping(value = "/imageUpload", produces = "text/html;charset=UTF-8")

public void imageUpload(@RequestParam(value = "upload", required = false) MultipartFile file,

HttpServletRequest request,HttpServletResponse response) throws Exception{

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

//CKEditor送出的很重要的一個參數

String callback = request.getParameter("CKEditorFuncNum"); 

String imageName = "";

//圖檔上傳目錄

String DirectoryName=PropertyUtils.getPropertyValueByKey("imagePath1");

//圖檔上傳位置

String imagePath = request.getSession().getServletContext().getRealPath("/"+DirectoryName);

File folder = new File(imagePath);

if (!folder.exists()) {

folder.mkdir();

}

if(!file.isEmpty()){

imageName=file.getOriginalFilename();

String path = imagePath+imageName;

//傳回伺服器的位址

String imageContextPath = request.getContextPath() + "/" + DirectoryName  + imageName;

File infoFile = new File(path);

InputStream is=file.getInputStream();

FileOutputStream fos = new FileOutputStream(infoFile);

byte[] bs = new byte[1024];

int len=is.read(bs);

while(len!=-1) {

fos.write(bs, 0, len);

len=is.read(bs);

}

is.close();

fos.flush();

fos.close();

out.println("<script type=\"text/javascript\">");  

   out.println("window.parent.CKEDITOR.tools.callFunction(" + callback  

               + ",'"  + imageContextPath + "','')");  

   out.println("</script>");  

}

繼續閱讀