下載插件:
http://pandao.github.io/editor.md/
將下載的插件解壓拷貝進(jìn)項(xiàng)目中
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/res/editor-md-master/css/editormd.css" />
<script type="text/javascript" src="${ pageContext.request.contextPath }/res/js/jquery-2.1.4.min.js"></script>
<script src="${pageContext.request.contextPath}/res/editor-md-master/editormd.min.js"></script>
<script type="text/javascript">
$(function(){
var testEditor = editormd({
id: "test-editormd",
height: 640,
width: "100%",
placeholder : "Markdown編輯器",
path: "${pageContext.request.contextPath}/res/editor-md-master/lib/",
toolbarIcons: function () {
// Or return editormd.toolbarModes[name]; // full, simple, mini
// Using "||" set icons align right.
return ["undo", "redo", "|", "watch", "fullscreen", "preview"]
},
//toolbar : false, // 關(guān)閉工具欄
codeFold: true,
searchReplace: true,
saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
htmlDecode: "style,script,iframe|on*", // 開(kāi)啟 HTML 標(biāo)簽解析局劲,為了安全性锭汛,默認(rèn)不開(kāi)啟
emoji: true,
taskList: true,
tocm: true, // Using [TOCM]
tex: true, // 開(kāi)啟科學(xué)公式 TeX 語(yǔ)言支持邮辽,默認(rèn)關(guān)閉
//previewCodeHighlight : false, // 關(guān)閉預(yù)覽窗口的代碼高亮,默認(rèn)開(kāi)啟
flowChart: true, // 疑似 Sea.js與 Raphael.js 有沖突迎献,必須先加載 Raphael.js 改备,Editor.md 才能在 Sea.js 下正常進(jìn)行婴梧;
sequenceDiagram: true, // 同上
//dialogLockScreen : false, // 設(shè)置彈出層對(duì)話框不鎖屏穗椅,全局通用辨绊,默認(rèn)為 true
//dialogShowMask : false, // 設(shè)置彈出層對(duì)話框顯示透明遮罩層,全局通用匹表,默認(rèn)為 true
//dialogDraggable : false, // 設(shè)置彈出層對(duì)話框不可拖動(dòng)门坷,全局通用宣鄙,默認(rèn)為 true
//dialogMaskOpacity : 0.4, // 設(shè)置透明遮罩層的透明度,全局通用默蚌,默認(rèn)值為 0.1
//dialogMaskBgColor : "#000", // 設(shè)置透明遮罩層的背景顏色冻晤,全局通用,默認(rèn)為 #fff
imageUpload: true,
imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL: "{:url('api/uploader/uploadEditorImg?pic_type=10')}",
onload: function () {
this.on('paste', function () {
console.log(1);
});
},
onpreviewing : function() {
this.watch();
console.log("onpreviewing =>", this, this.id, this.settings);
// on previewing you can custom css .editormd-preview-active
},
onpreviewed : function() {
console.log("onpreviewed =>", this, this.id, this.settings);
this.unwatch();
}
});
/**
* 上傳圖片
*/
$("#test-editormd").on('paste', function (ev) {
var data = ev.clipboardData;
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (var index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
reader.onload = function (event) {
var base64 = event.target.result;
console.log(base64);
//ajax上傳圖片
$.ajax({
url : "${pageContext.request.contextPath}/topic/uploadimg",
type : 'post',
data : {'base':base64},
async : true,
dataType: 'json',
success : function (res) {
if (res.code === 1) {
//新一行的圖片顯示
testEditor.insertValue("\n![" + "image.png" + "](${pageContext.request.contextPath}/" + res.path + ")");
}
},
error : function(){
alert('圖片上傳錯(cuò)誤');
}
});
}; // data url!
var url = reader.readAsDataURL(blob);
}
}
});
})
</script>
</head>
<body>
<form action="${ pageContext.request.contextPath }/article/addArticle">
<div class="editormd" id="test-editormd">
<textarea class="editormd-markdown-textarea" name="topic_markdown_content" id = "topic_markdown_content">${topic.topic_markdown_content}</textarea>
</div>
<button>提交</button>
</form>
</body>
</html>
解密后保存工具類
package com.neuedu.util;
import java.io.FileOutputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
public class picEncode {
/**
* @Description: 將base64編碼字符串轉(zhuǎn)換為圖片
* @Author:
* @CreateTime:
* @param imgStr
* base64編碼字符串
* @param path
* 圖片路徑-具體到文件
* @return
*/
public static boolean generateImage(String imgStr, String path) {
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// 解密
byte[] b = decoder.decodeBuffer(imgStr);
// 處理數(shù)據(jù)
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
實(shí)體類绸吸,用來(lái)響應(yīng)頁(yè)面請(qǐng)求
package com.neuedu.util;
public class imgUploadBackData {
private String path;
private int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
Controller或Servlet
package com.neuedu.servlet;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.neuedu.util.imgUploadBackData;
import com.neuedu.util.picEncode;
@WebServlet("/topic/uploadimg")
public class UploadImgServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strTemp = request.getParameter("base");
System.out.println(strTemp);
strTemp = strTemp.replace("data:image/png;base64,","");
// String strPath = this.getClass().getClassLoader().getResource("/../../upload").getPath();
String strPath = request.getServletContext().getRealPath(File.separator+"upload");
String strUUid = UUID.randomUUID().toString();
System.out.println(strPath);
File file = new File(strPath);
if(!file.exists())
{
file.mkdirs();
}
String strSavePath = strPath+File.separator+strUUid+".jpg";
picEncode.generateImage(strTemp,strSavePath);
imgUploadBackData iubd = new imgUploadBackData();
iubd.setPath("upload"+File.separator+strUUid+".jpg");
iubd.setCode(1);
String strJson = JSON.toJSONString(iubd);
response.getWriter().println(strJson);
}
}
提交表單時(shí)可以觀察請(qǐng)求體中的參數(shù)鼻弧,會(huì)發(fā)現(xiàn)內(nèi)容包含兩部分,一部分是markdown語(yǔ)法部分惯裕,方便發(fā)布者修改文章温数,還有一部分是markdown渲染出的html部分绣硝,是作為展示的蜻势,所以,對(duì)應(yīng)數(shù)據(jù)庫(kù)中應(yīng)該也有兩個(gè)字段支持鹉胖。