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 提交表单和上传图片
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章