SpringBoot MarkDown editor.md实现图片上传

束俊英
2023-12-01

SpringBoot集成 MarkDown editor.md实现图片上传

  1. 通过在html嵌入的js代码中配置MarkDown功能
 <script type="text/javascript">
        $(function() {
            var editor = editormd("question-editor", {
                width  : "100%",
                height : 500,
                path   : "/js/lib/",
                delay  : 0,
                watch  : false,
                placeholder: "请输入问题描述",
                imageUpload       : true,//设置为true后就开启了图片文件上传
                imageFormats      : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                imageUploadURL    : "/upload"
            });
        });
    </script>
<!-- 通过F12查看控制台,看需要什么资源文件,就拷贝到static目录下-->

  1. 官方文档
  • 同域上传

  • 所需要的配置

Settings

{
    imageUpload    : true,
    imageFormats   : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
    imageUploadURL : "./php/upload.php",
}

JSON data

{
    success : 0 | 1,           // 0 表示上传失败,1 表示上传成功
    message : "提示的信息,上传成功或上传失败及错误信息等。",
    url     : "图片地址"        // 上传成功时才返回
}
  1. SpringBoot实现文件上传
 @ResponseBody
    @PostMapping("/upload")
    public JSONObject upLoad(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file
    ) {
        JSONObject object = new JSONObject();
        try {
            //先创建文件夹
            //先获取在当前系统下的文件夹路径
            String osName = System.getProperty("os.name");
            String realPath;
            if (osName.toLowerCase().startsWith("win")) {
                realPath = "D:/community/upload/";
            } else {
                realPath = "/resources/community/upload/";
            }
            File myFlie = new File(realPath);
            if (!myFlie.exists()) {
                myFlie.mkdirs();
            }
            //获取上传文件的文件名
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            fileName = uuid + "_" + fileName;
            file.transferTo(new File(realPath, fileName));
            object.put("success", 1);
            object.put("message", "上传成功");
            object.put("url", "/upload/" + fileName);
        } catch (Exception e) {

            object.put("success", 0);
            object.put("message", "上传失败");
        }

        return object;

    }
 类似资料: