editorMd应该算是目前比较主流也比较好用的markdown编辑器插件了,简单记录一下使用方法,直接上代码。
(使用了semantic ui,其实只要有一个带id的div包裹一个textarea就可以使用了)
<div class="required field">
<div id="mdContent" style="z-index: 1 !important;">
<textarea th:text="*{content}" name="content" style="display: none">
textarea>
div>
div>
<script src="../../static/js/uploadImg.js"></script>//引入粘贴和拖拽上传图片功能
<script>
var contentEditor;
$(function() {
//markdown编辑器的初始化
contentEditor = editormd("mdContent", {
placeholder: '马上开始撰写博客内容吧...',
width : "100%",
height : 700,
syncScrolling : "single",
//path : "../../static/lib/editormd/lib/",//静态页面路径
path : "/lib/editormd/lib/",
emoji:true,
tocm: true,
tex: true,
dialogLockScreen: false,
dialogShowMask: false,
dialogDraggable: false,
dialogMaskOpacity:0.4,
dialogMaskBgColor:"#000",
imageUpload : true,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "/admin/blogs/editormdPicUpload",
onload : function() {
initPasteDragImg(this); //允许粘贴和拖拉图片到editormd
}
});
});
</script>
(uploadImg实现粘贴拖拽上传图片部分)
function initPasteDragImg(Editor){
var doc = document.getElementById(Editor.id)
doc.addEventListener('paste', function (event) {
var items = (event.clipboardData || window.clipboardData).items;
var file = null;
console.log(items)
console.log(items.length)
if (items && items.length) {
// 搜索剪切板items
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile();
break;
}
}
}
else {
console.log("当前浏览器不支持");
return;
}
if (!file) {
console.log("粘贴内容非图片");
return;
}
uploadImg(file,Editor);
});
var dashboard = document.getElementById(Editor.id)
dashboard.addEventListener("dragover", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("dragenter", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("drop", function (e) {
e.preventDefault()
e.stopPropagation()
var files = this.files || e.dataTransfer.files;
uploadImg(files[0],Editor);
})
}
function uploadImg(file,Editor){
var formData = new FormData();
var fileName=new Date().getTime()+"."+file.name.split(".").pop();
formData.append('editormd-image-file', file, fileName);
$.ajax({
url: Editor.settings.imageUploadURL,
type: 'post',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (msg) {
var success=msg['success'];
if(success==1){
var url=msg["url"];
if(/\.(png|jpg|jpeg|gif|bmp|ico)$/.test(url)){
Editor.insertValue("![]("+msg["url"]+")");
}else{
Editor.insertValue("[下载附件]("+msg["url"]+")");
}
}else{
console.log(msg);
alert("上传失败");
}
}
});
}
(处理editorMd图片上传请求,editormd-image-file名字固定,不可以改)
@RequestMapping("/editormdPicUpload")
@ResponseBody
public JSONObject editormdPicUpload(@RequestParam(value = "editormd-image-file",required = false)MultipartFile image) throws IOException{
JSONObject jsonObject=new JSONObject();
try{
String url = "/upload-images/"+fileUtil.save(image, imageSavepath, image.getOriginalFilename());
jsonObject.put("success",1);
jsonObject.put("message","上传成功~");
jsonObject.put("url",url);
}
catch (Exception e){
jsonObject.put("success",0);
jsonObject.put("message","出错啦~");
}
return jsonObject;
}
(fileUtil处理文件上传):
/**
* 功能描述: 处理文件上传
* @Param: [file 文件, path 文件存储路径, fileName 原文件名]
* @Return: java.lang.String
* @Author: Sichengluis
* @Date: 2021/2/18 12:03
*/
public static String save(MultipartFile file, String path, String fileName){
String newFileName = getFileName(fileName);
// 生成新的文件名
String realPath = path + newFileName;
//使用原文件名
// String realPath = path + "/" + fileName;
File dest = new File(realPath);
//判断文件父目录是否存在
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
try {
//保存文件
file.transferTo(dest);
return newFileName;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
(配置上传文件路径):
/**
* 功能描述: 配置扫描static下各个文件夹的静态资源
* @Param: [registry]
* @Return: void
* @Author: Sichengluis
* @Date: 2021/2/16 20:18
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");//配置浏览器直接访问static下的静态资源
registry.addResourceHandler("/upload-images/**").addResourceLocations("file:" + imageSavePath);//配置图片物理存储路径和虚拟访问路径
}