markdown编辑器
一、demo运行
1、从markdown编辑器官网进行demo下载,连接地址:https://pandao.github.io/editor.md/,附带其他可用连接,可以进行markdown编辑器的使用https://pandao.github.io/editor.md/examples/
2、可以看到文件夹目录如下:
3、先运行一下examples文件夹的simple.html可以看到markdown编辑器的使用效果:
4、先尝试把demo拉进项目,因为拉进项目之后文件目录会改变,更改引入的js以及css文件路径:
注意更改引入的css和js路径,在function内部还有lib路径也要对应。
<% String path = request.getContextPath();%>
<link rel="stylesheet" href="<%=path %>/editors/examples/css/style.css"/>
<link rel="stylesheet" href="<%=path %>/editors/css/editormd.css"/>
<script src="<%=path %>/editors/examples/js/jquery.min.js"></script>
<script src="<%=path %>/editors/editormd.min.js"></script>
path : “<%=path %>/editors/lib/”,
现在就可以运行成功编辑器。
二、添加进项目
1、把编辑器加入已有项目只需要添加关键文件夹即可,操作如下:
- examples文件中是使用PHP做的所有示例(可以在文档编辑器里打开,并查看源代码)
- lib中是editor.md所依赖的第三方js资源
- plugins中是如emoji表情支持、代码格式化等插件
2、更改引入的css和js路径,在function内部还有lib路径也要对应
3、更改配置
<script type="text/javascript">
var testEditor;
$(function() {
testEditor = editormd("test-editormd", {
width : "90%",
height : 640,
syncScrolling : "single",
path : "<%=path %>/editors/lib/",
saveHTMLToTextarea:true,//用于表单提交
//用于文件图片上传
imageUpload:true,
imageFormats:["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "<%=path%>/editor/editorMDUpload",//请求地址
onload:function(){
success:0|1 ; //0代表上传失败,1代表上传成功
message:"提示的信息,上传成功或者失败以及错误信息";
url:"上传成功时才返回"
},
toolbarIcons : function(){
//根据给的文档可以了解到每一项的意义或者不同的工具栏展示情况
return editormd.toolbarModes['full'];// full, simple, mini
/* [ "undo", "redo", "|",
"bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
"h1", "h2", "h3", "h4", "h5", "h6", "|",
"list-ul", "list-ol", "hr", "|",
"link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
"goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
"help", "info"] */
},
});
});
</script>
以下几项是在前后台数据传输过程中起着关键作用:
saveHTMLToTextarea:true,//用于表单提交
//用于文件图片上传
imageUpload:true,
imageFormats:["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "<%=path%>/editor/editorMDUpload",//请求地**址
**onload:function(){
success:0|1 ; //0代表上传失败,1代表上传成功
message:"提示的信息,上传成功或者失败以及错误信息";
url:"上传成功时才返回"
},
后端要想获得第二个textarea中的值,首先需要打开editor.md的saveHTMLToTextarea : true
4、 在body内添加div
<input type="text" placeholder="请输入标题" id="title" name="title" autocomplete="off">
<input name="my_submit" id="my_submit" value="提交" type="button">
<div id="test-editormd">
<textarea id="editor-md-doc" name="editor-md-doc" style="display:none;"></textarea>
<textarea id="editor-md-html" name="editor-md-html"></textarea>
</div>
div的id应与script配置中 testEditor = editormd(“test-editormd”, {})保持一致。
三、表单提交
<link rel="stylesheet" href="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"/>
/* 信息提交 */
function submit_article() {
//数据初始化
var title = $("#title").val();
var markdownContent = testEditor.getMarkdown();
var htmlContent = testEditor.getHTML();
alert("title"+title);
alert("markdownContent"+markdownContent);
alert("htmlContent"+htmlContent);
//数据传递
$.ajax({
url: "<%=path%>/editor/editorContent",
data: JSON.stringify({title: title,
htmlContent: htmlContent,
markdownContent: markdownContent}),
type: "POST",
contentType: 'application/json',
success: function () {
alert("发布成功");
},
error: function () {
alert("发布失败");
}
})
}
后端接收Article,具有以下属性
private Long ID;
private String title;
private String htmlContent;
private String markdownContent;
//因为内容过大,可以把字段类型设置成为clob,可以实现多数据插入
Controller接收:
@RequestMapping(value = "editorContent",method = RequestMethod.POST)
public boolean articleContent(@RequestBody Article article){
//进行数据操作插入数据库
}
就可实现编辑器传入数据到数据库操作
四、数据获取
提交后,后端获取到MD文档内容后,存在数据库中,然后在页面展示时,我们需要把MD语法文档,转换为HTML语法,在前端就行内容显示
1、在页面引入对应的js
<script src="/smart-api/htdocs/mdeditor/js/jquery.min.js"></script>
<script src="/smart-api/htdocs/mdeditor/lib/marked.min.js"></script>
<script src="/smart-api/htdocs/mdeditor/lib/prettify.min.js"></script>
<script src="/smart-api/htdocs/mdeditor/lib/raphael.min.js"></script>
<script src="/smart-api/htdocs/mdeditor/lib/underscore.min.js"></script>
<script src="/smart-api/htdocs/mdeditor/lib/sequence-diagram.min.js"></script>
<script src="/smart-api/htdocs/mdeditor/lib/flowchart.min.js"></script>
<script src="/smart-api/htdocs/mdeditor/lib/jquery.flowchart.min.js"></script>
<script src="/smart-api/htdocs/mdeditor/js/editormd.min.js"></script>
2、添加一个div作为数据显示区域
<div id="test" style="float:left">
<h1>数据展示</h1>
//标题展示
<input type="text" id="getTitle" name="getTitle" readonly="readonly">
//内容展示
<div class="markdown-body editormd-preview-container"></div>
</div>
3、再加入数据交流的js
/*数据获取 */
function search_article(){
var title = $("#search").val();
alert("搜索标题是:"+title);
$.ajax({
url : "<%=path%>/editor/search",
data : JSON.stringify({title:title}),
type : "POST",
contentType : 'application/json',
dataType : 'json',
/* success : function(){
alert("数据查询成功");
}, */
success : function(data) { //如果请求成功,返回数据。
$("#getTitle").val(data.title);
$(".markdown-body").html(data.htmlContent);
alert(data.htmlContent);
},
error : function(){
alert("数据查询失败");
}
})
}
</script>
五、文件上传
1、在配置中添加对应的文件上传配置,前面已经配置好
2、controller编写(图片上传到工程目录下):
//处理文件上传
@RequestMapping(value="/editorMDUpload")
public @ResponseBody Map<String,Object> demo(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file, HttpServletRequest request) {
String UPLOADED_FOLDER = "D://Dev_DAM//workspace//editor//src//main//webapp//resource//upload//";//项目路径,即图片上传目的文件夹位置
Map<String,Object> resultMap = new HashMap<String,Object>();
String realPath = UPLOADED_FOLDER;
String fileName = file.getOriginalFilename();
/*
*
System.out.println(request.getLocalPort()); //8080
System.out.println(request.getLocalAddr()); //127.0.0.1
//端口及项目名称获取
String result = "http://";
String IP = request.getLocalAddr();
int port = request.getLocalPort();
StringBuilder sb = new StringBuilder();
String proPath = System.getProperty("user.dir");
String proName = proPath.substring(proPath.lastIndexOf("\\")+1, proPath.length());
sb.append(result).append(IP).append(":").append(String.valueOf(port)).append("/").append(proName);
System.out.println("sb:"+sb);
*/
// 获取物理路径
String contextPath = request.getSession().getServletContext().getRealPath("");
// 获取网络路径
String basePath = request.getScheme()+"://"+request.getServerName()+":"
+request.getServerPort() + request.getContextPath();
System.err.println(contextPath);
System.out.println(basePath);
//使用NIO进行图片上传
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
resultMap.put("success", 1);
resultMap.put("message", "上传成功!");
resultMap.put("url",basePath+"/resource/upload/"+fileName);
} catch (Exception e) {
resultMap.put("success", 0);
resultMap.put("message", "上传失败!");
e.printStackTrace();
}
System.out.println(resultMap.get("success"));
return resultMap;
}
1、@RequestParam(value = “editormd-image-file”, required = false),value值是固定的,为了和markdown前端有个对应。注释掉的地方是另外一种获取地址方式。
2、controller需要返回给前端三个数据,success,url以及message
六、总结
在过程中出现很多不在预期内的小bug
1、问题:表格样式不显示,只显示数据
解决办法:自定义表格css样式,表格显示时候样式就会添加
table {
width: 80%; /*表格宽度*/
max-width: 65em; /*表格最大宽度,避免表格过宽*/
border: 1px solid #dedede; /*表格外边框设置*/
margin: 15px auto; /*外边距*/
border-collapse: collapse; /*使用单一线条的边框*/
empty-cells: show; /*单元格无内容依旧绘制边框*/
}
table th,table td {
height: 35px; /*统一每一行的默认高度*/
border: 1px solid #dedede; /*内部边框样式*/
padding: 0 10px; /*内边距*/
text-align:center;
}
2、问题:文件上传,无法上传到项目目录下
解决办法:使用一般的文件上传会出现绝对路径相对路径不匹配,改用NIO文件传输方式,可以解决这个问题。
上一篇: markdown编辑器
下一篇: markdown编辑器