Spring 上傳圖片並將返回的圖片地址插入到 Markdown 編輯器

關於本篇文章

在寫博客的時候,會有上傳圖片的功能,自己實現一個簡單版本 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

測試結果
在這裏插入圖片描述

第二章 上傳圖片

後臺將提交的圖片保存到自定義位置,這個位置的圖片可以通過網絡路徑訪問

文件結構大致如下

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 = '![' + picName + '](' + data + ')';

                // 插入到內容焦點中
                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>

注意:這裏沒有進行文件夾的檢索,運行前需要手動創建圖片位置的文件夾

運行

在這裏插入圖片描述

附錄 A 參考資料

  1. showdown 官方網站
  2. showdown Tutorial: Markdown editor using Showdown
  3. Spring GUIDES:Uploading Files
  4. 使用 FormData 提交表單和上傳圖片
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章