summernote富文本最全總結

富文本我使用過UEditor以及summernote,只是使用的插件不一樣,使用的方法大體還是相同的。這裏進行一個總結,方便自己,方便他人。這裏以summernote使用爲例進行總結。

先說說富文本字段問題。我使用的是oracle數據庫,用clob字段,長度爲4000,CLOB使用CHAR來保存數據,把CLOB看成字符串類型即可。

實體類中用String接收

1.從summernote官網下載插件,放到自己的項目靜態文件夾中。summernote官網地址:https://summernote.org/

2.在項目中的html文件中引入js和css。

<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote.js"></script> 
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.8/summernote-zh-CN.js.js"></script>
如果項目中使用了bootstrap4,還需要引入下面的css
	<link th:href="http://cdnjs.cloudflare.com/ajax/libs/summernote/summernote-bs3.css}" rel="stylesheet"/>

3.在html寫一個div來放置summernote
<div id="summernote">Hello Summernote</div>

4.在html中初始化summernote.

			var $summernote = $('#summernote').summernote({
						height : 300,
						width:660,
						tabsize : 2,
						lang : 'zh-CN',
						minHeight : null,
						maxHeight : null,
						focus : true,
						//調用圖片上傳
						callbacks : {
							onImageUpload : function(files) {
								sendFile($summernote, files[0]);
							}
						}
					});
                    //sendFile(上傳圖片到服務器,如果不調用callbacks,圖片默認保存到數據庫,會            
                      導致讀取數據卡慢
					function sendFile($summernote, file) {
						var formData = new FormData();
						formData.append("file", file);
						$.ajax({
							url : "../imageUpload",
							data : formData,
							cache : false,
							contentType : false,
							processData : false,
							type : 'POST',
							success : function(data) {
								var path = '../../ShowPictures.do?imageurl='
										+ data;
								$summernote.summernote('insertImage', path,
										function($image) {
											console.log(path)
											$image.attr('src', path);
										});
							}
						});
					}

5.html編輯完之後,就是要保存到數據庫了,那summernote怎麼保存呢?

使用下面的寫法就可以獲取summernote的值了

var markupStr = $('#summernote').summernote('code');

6.但是如果圖片不保存到服務器,在summernote中上傳圖片時,是很順利的,圖片可以直接上傳到數據庫,編輯的時候也可以直接回顯,但是,上傳到服務器,圖片要進行回顯的話,需要對文件流進行處理。上文提到的imageUpload和ShowPictures.do方法很重要。一個是圖片上傳,一個是圖片回顯。

7.先說imageUpload方法

@ResponseBody
    @RequestMapping("/imageUpload")
    public String imageUpload(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "file", required = false)MultipartFile image) {
		Map<String,Object> map = new HashMap<String, Object>();
		String fileName = image.getOriginalFilename(); //獲取文件名
		String names[] = fileName.split("\\.");
		String path = null;
    	if (!image.isEmpty()) {
    		//path自己定義
    		
    	        String todayDate=DateUtils.dateTime();//這裏希望每天上傳的圖片在一個文件夾裏 
                面
    		    String sname = fileName.substring(fileName.lastIndexOf("."));//獲取圖片後            
                綴名
    	        long timeStamp = System.currentTimeMillis();//獲取時間戳,給圖片重新命名, 
                以訪圖片中非法字符影響程序的使用
				String path1 = "/app/yxdat/classroom/courseware/"+todayDate;//此路徑不帶圖 
                片,用於上傳
				String imageName=timeStamp+sname;//圖片名
				File targetFile1 = new File(path1, imageName);
				path=path1+"/"+imageName;//此路徑保存到數據庫
				File dir=targetFile1.getParentFile();
				if (!dir.exists()) {
					dir.mkdirs();
				}
                OutputStream out=null;
			    InputStream in=null;             
			    int length;
         try {    
    	  	out = new BufferedOutputStream(new FileOutputStream(targetFile1));
			in = new BufferedInputStream(image.getInputStream());
            byte[] buf = image.getBytes();//文件二進制
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
                out.flush();
            }
            in.close();
            out.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            } 
           map.put("code", 0);
           map.put("path", path);
       }else {
    	   map.put("code", 500);
           map.put("path", "");
       }
    	//String httpurl=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+path;
    	
    	return path;//這個路徑很重要,是要傳到前臺的,前臺富文本回顯根據這個路徑回顯,從服務器獲取圖片路徑(帶文件名的路徑),然後用二進制流讀取到富文本
	}
    

8.再說ShowPictures.do。這裏直接進行調用即可,不再解說。


	@RequestMapping("/ShowPictures.do")
	public void ImagesTransComMethod(String imageurl, HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("multipart/form-data");
		ServletOutputStream out = null;
		try {
			FileInputStream fips = null;
			out = response.getOutputStream();
			try {
				String fzpath =new String(imageurl.getBytes(), "UTF-8");
				File file = new File(fzpath);
				if (!file.exists()) {
					return;
				}
				fips = new FileInputStream(new File(fzpath));
				log.info(fips.available());

				int i = 0;
				byte[] buffer = new byte[4096];
				while ((i = fips.read(buffer)) != -1) {
					out.write(buffer, 0, i);
				}
				out.flush();
				fips.close();
			} catch (Exception e) {
				log.warn("處理文件流失敗:" + e.getMessage());
				e.printStackTrace();			
			} finally {
				if (out != null) {
					try {
						out.close();
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
				if (fips != null) {
					try {
						fips.close();
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	

9.富文本保存成功之後,對於編輯可能是一個問題,需要兩個div配合回顯,不然會直接顯示html純文本,插入到數據庫的代碼直接顯示出來了。

這裏請參考我的另一個博客。

https://blog.csdn.net/fu18838928050/article/details/106652993

10.如有疏漏或疑惑,敬請糾正或提問。謝謝大家

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章