目錄
關于本篇文章
第一章 markdown 編輯器
第二章 上傳圖片
附錄 A 參考資料
關于本篇文章
在寫博客的時候,會有上傳圖片的功能,自己實現一個簡單版本 markdown 編輯器附帶上傳圖片功能
案例會涉及到的知識包括但不限于
- IntelliJ IDEA
- Spring Boot
- JavaScript
- JQuery
- Thymeleaf
- Markdown 語法
第一章 markdown 編輯器
markdown 語言轉換功能,有很多 js 插件,這里選用 showdown
在Showdowm 官網下載 showdown.min.js,放到項目里
創建一個頁面 uploadForm.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div>
<textarea id="content" rows="10" onkeyup="run()" style="float: left; margin-right: 100px;"></textarea>
<div id="targetDiv"></div>
</div>
<script src="../static/showdown.min.js" th:src="@{showdown.min.js}"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function run() {
var text = $('#content').val(),
target = document.getElementById('targetDiv'),
converter = new showdown.Converter(),
html = converter.makeHtml(text);
target.innerHTML = html;
}
</script>
</body>
</html>
-
run()
方法是將<textarea>
中的內容轉換成 html
測試結果
markdown.png
第二章 上傳圖片
后臺將提交的圖片保存到自定義位置,這個位置的圖片可以通過網絡路徑訪問
文件結構大致如下
src/
+- main/
+- java/
+- com/
+- lee/
+- fileupload/
+- controller/
+- FileUploadRestController.java
+- FileuploadApplication.java
+- sources/
+- static/
+- showdown.js
+- showdown.js.map
+- showdown.min.js
+- showdown.min.js.map
+- template/
+- uploadForm.html
+- application.properties
首先設置自己電腦放圖片的位置,在 application.properties 配置如下:
img.upload-path=/Users/lee/resources/static/img/
spring.resources.static-locations=classpath:/META-NF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${img.upload-path}
img.upload-path
是圖片位置spring.resources.static-locations
需要手動將所有資源添加進去
因為 markdown 需要知道圖片的網絡位置,才能正確獲得圖片,在這里圖片上傳成功后會返回圖片網絡地址,這種情況用 REST API 很合適
package com.lee.fileupload.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
@RestController
@RequestMapping("/api")
public class FileUploadRestController {
@Value("${img.upload-path}")
private String uploadPath;
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
try {
Files.write(Paths.get(uploadPath + file.getOriginalFilename()), file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return "http://localhost:8080/" + file.getOriginalFilename();
}
}
在 uploadForm.html 頁面中添加圖片上傳,并用 ajax 進行提交和插入返回的圖片網絡地址
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div>
<form id="uploadImageForm" method="POST" enctype="multipart/form-data" action="/" >
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" multiple /></td></tr>
<tr><td></td><td><input id="upload" type="button" value="Upload" /></td></tr>
</table>
</form>
<textarea id="content" rows="10" onkeyup="run()" style="float: left; margin-right: 100px;"></textarea>
<div id="targetDiv"></div>
</div>
<script src="../static/showdown.min.js" th:src="@{showdown.min.js}"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$('#upload').click(function(){
$.ajax({
url:"/api/",
type:"post",
data:new FormData(document.getElementById('uploadImageForm')),
processData:false,
contentType:false,
success:function (data) {
// 生成圖片網址
var dataArray = data.split('/');
var picName = dataArray[dataArray.length - 1];
var picURL = '';
// 插入到內容焦點中
var text = $('#content').val();
var foucsStart = document.getElementById('content').selectionStart;
var len = text.length;
var subStr = '';
if (foucsStart == len)
text += '\n\n' + picURL + '\n\n';
else {
subStr = text.substr(foucsStart, 1);
text = text.replace(subStr, '\n\n' + picURL + '\n\n' + subStr);
console.log(text);
}
$('#content').val(text);
run(); // 手動觸發 markdown 文字轉換
},
error:function (e) {
}
});
});
function run() {
var text = $('#content').val(),
target = document.getElementById('targetDiv'),
converter = new showdown.Converter(),
html = converter.makeHtml(text);
target.innerHTML = html;
}
</script>
</body>
</html>
- 這里添加一個
<form>
用于上傳圖片 - 在
<script>
中添加$('#upload').click()
按鈕觸發事件,用于 ajax 上傳圖片,并將返回的圖片地址插入到<textarea>
中
注意:這里沒有進行文件夾的檢索,運行前需要手動創建圖片位置的文件夾
運行
QQ20181106-144707@2x.png