SpringBoot+Editormd實現markdown文字編輯和圖片上傳
阿新 • • 發佈:2019-02-19
富文字編輯是開發過程中常用的功能之一,而markdown是開發人員最親睞的編輯格式,此刻,我也正在使用CSDN的markdown編輯器進行編輯。剛好有了一些想法,所以實現了這個功能。
Markdown文字編輯功能實現
Editormd專案地址,Editormd的基本實現非常簡單,只需要在html中引入必要的css檔案(此處使用了thymeleaf)
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
<title>Edit</title>
<link rel="stylesheet" th:href="@{/css/style.css}"
href="/css/style.css"/>
<link rel="stylesheet" th:href="@{/editormd/css/editormd.css}"
href ="/editormd/css/editormd.css"/>
<link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon"/>
在html中寫上兩個帶有明確class:editormd-markdown-textarea和editormd-html-textarea的標籤
<div class="editormd" id="test-editormd">
<textarea class="editormd-markdown-textarea" name="test-editormd-markdown-doc" id="content"></textarea>
<!-- 第二個隱藏文字域,用來構造生成的HTML程式碼,方便表單POST提交,這裡的name可以任意取,後臺接受時以這個name鍵為準 -->
<textarea class="editormd-html-textarea" name="editormd-html-textarea" id="htmlContent"></textarea>
</div>
最後我們進行引入js後進行初始化操作即可
<script th:src="@{/js/jquery.min.js}" src="/js/jquery.min.js"></script>
<script th:src="@{/editormd/js/editormd.js}" src="/editormd/js/editormd.js"></script>
<script type="text/javascript">
$(function() {
editormd("test-editormd", {
width : "90%",
height : 640,
syncScrolling : "single",
//你的lib目錄的路徑,我這邊用JSP做測試的
tocm : true, // Using [TOCM]
tex : true, // 開啟科學公式TeX語言支援,預設關閉
flowChart : true, // 開啟流程圖支援,預設關閉
path : "/editormd/lib/",
//這個配置在simple.html中並沒有,但是為了能夠提交表單,使用這個配置可以讓構造出來的HTML程式碼直接在第二個隱藏的textarea域中,方便post提交表單。
saveHTMLToTextarea : true
});
});
此時我們在後臺中寫新增
@RequestMapping("edit")
public String editor(){
return "edit";
}
可見如下效果
當我們新增基本的java物件並且在html中新增按鈕之後我們就可以將資料傳遞到後臺了。
@Id // 主鍵
@GeneratedValue(strategy = GenerationType.IDENTITY) // 自增長策略
private Long id; // 使用者的唯一標識
//@NotEmpty(message = "標題不能為空")
@Column(nullable = false, length = 50) // 對映為欄位,值不能為空
private String title;
//@NotEmpty(message = "摘要不能為空")
@Column(nullable = false) // 對映為欄位,值不能為空
private String summary;
@Lob // 大物件,對映 MySQL 的 Long Text 型別
//@NotEmpty(message = "內容不能為空")
@Column(nullable = false) // 對映為欄位,值不能為空
private String content;
@Lob // 大物件,對映 MySQL 的 Long Text 型別
//@NotEmpty(message = "內容不能為空")
@Column(nullable = false) // 對映為欄位,值不能為空
private String htmlContent; // 將 md 轉為 html
public Long getId() {
return id;
}
//省略get,set方法
js中新增
$("#submitBtn").click(
function () {
alert("點選按鈕了");
submitblog();
}
)
function submitblog() {
var title = $("#title").val();
var content = $("#content").val();
var htmlContent = $("#htmlContent").val();
$.ajax({
url: "submit",
data: {title: title, content:content,htmlContent:htmlContent},
success:function () {
alert("釋出成功");
},
error:function () {
alert("釋出失敗");
}
})
}
Controller中新增接受方法
@RequestMapping("submit")
@ResponseBody
public void submit(Blog blog){
System.out.println(blog.getContent());
System.out.println(blog.getHtmlContent());
blogRepository.save(blog);
}
即可儲存
實現文字上傳功能
前端實現
Editormd的文字上傳功能在前端的實現也非常簡單,只需要在前端js初始化的程式碼中加入
imageUpload : true,
imageFormats : [ "jpg", "jpeg", "gif", "png", "bmp", "webp" ],
imageUploadURL : "/uploadimg",
onload: function () {
//console.log('onload', this);
//this.fullscreen();
//this.unwatch();
//this.watch().fullscreen();
this.width("100%");
this.height(480);
//this.resize("100%", 640);
}
onload方法為上傳圖片的回撥方法,可以在這裡設定圖片的一些屬性
但是實際測試過程中,發現這些屬性並沒有什麼作用,網上也沒有對應的例子。因此,這一步需要好好探究
後端實現
@RequestMapping(value="/uploadimg")
public @ResponseBody Map<String,Object> demo(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file, HttpServletRequest request) {
Map<String,Object> resultMap = new HashMap<String,Object>();
System.out.println(request.getContextPath());
String realPath = UPLOADED_FOLDER;
String fileName = file.getOriginalFilename();
System.out.println(fileName);
/* File targetFile = new File(realPath, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}*/
//儲存
try {
/* file.transferTo(targetFile);*/
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",UPLOADED_FOLDER+fileName);
} catch (Exception e) {
resultMap.put("success", 0);
resultMap.put("message", "上傳失敗!");
e.printStackTrace();
}
System.out.println(resultMap.get("success"));
return resultMap;
}
此處有兩個需要注意的點
- 由於SpringBoot自帶的Tomcat的原因,導致圖片無法上傳到專案目錄下,自帶的Tomcat的臨時目錄的存取許可權有問題,因此此處我們使用了一個指定目錄
- Editormd前端規定了後臺必須返回給前端一個map且形式為{“success”:1,message:”上傳成功”,”url”:url},這裡需要注意一下。
- 其次,使用簡單的file檔案寫入也許會存在問題,因此,我們這裡採用了NIO的寫入方式
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);