springboot-使用editor.md及使用阿里云OSS作图床

该博客是为了后面搭建博客做的前期准备

使用阿里云OSS作图床

在使用markdown写博客的时候,通常都需要放图片,而markdown需要图片的地址,网络图片还好说,但是本地图片就不太好办了,因此我们可以使用阿里云的OSS来作为我们的图床,把图片上传到阿里云的OSS,然后返回图片的URL用作地址
在这里插入图片描述
步骤:
1.注册阿里云,购买OSS
阿里云OSS
2.创建工程
在这里插入图片描述
导入相应的依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 阿里云OSS-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.配置OSS的相关属性

public class AliyunOssConfigConstant {
    private AliyunOssConfigConstant(){}

    //仓库名称
    public static final String BUCKE_NAME = "你的bucket名称";
    //地域节点
    public static final String END_POINT = "你的endpoint";
    //AccessKey ID
    public static final String AccessKey_ID = "你的AccessKey ID";
    //Access Key Secret
    public static final String AccessKey_Secret = "你的Access Key Secret";
    //仓库中的文件夹
    public static final String FILE_HOST = "你的文件夹名称";
}

除了通过常量类来配置,你还可以通过配置文件来配置,再将其注入到一个配置类中

4.编写工具类,即文件上传的方法

@Component
public class AliyunOssUtil {
    private static String File_URL;
    private static String bucketName = AliyunOssConfigConstant.BUCKE_NAME;
    private static String endPoint = AliyunOssConfigConstant.END_POINT;
    private static String accessKeyId = AliyunOssConfigConstant.AccessKey_ID;
    private static String accessKeySecret = AliyunOssConfigConstant.AccessKey_Secret;
    private static String fileHost = AliyunOssConfigConstant.FILE_HOST;

    public  String upLoad(File file){
        boolean isImage = true;
        try {
            Image image = ImageIO.read(file);
            isImage = image == null?false:true;
        }catch (Exception e){
            e.printStackTrace();
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(file == null){
            return null;
        }

        OSSClient ossClient = new OSSClient(endPoint,accessKeyId ,accessKeySecret );
        try {
            if(!ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //设置文件路径,这里再通过时间分成子文件夹
            String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "")+"-"+file.getName());
            //如果是图片
            if(isImage){
                File_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
            }else {
                File_URL = "非图片,不可预览。文件路径为:" + fileUrl;
            }
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置公开读权限
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
        return File_URL;
    }
}

5.编写controller

@Controller
@RequestMapping("/oss")
public class AliyunOssController {
    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    @RequestMapping("/upload")
    public String testUpload(@RequestParam("file")MultipartFile file, Model model){
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        try {
            if(file != null){
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream outputStream = new FileOutputStream(newFile);
                    outputStream.write(file.getBytes());
                    outputStream.close();
                    file.transferTo(newFile);
                    //返回图片的URL
                    String url = aliyunOssUtil.upLoad(newFile);
                    model.addAttribute("url",url );
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}

6.编写界面,界面可实现图片预览

index.html

<body>
    <form action="/oss/upload" enctype="multipart/form-data" method="post">
        <div class="form-group" id="group">
            <input type="file" id="img_input" name="file" accept="image/*">
            <label for="img_input" ></label>
        </div>
        <button type="submit" id="submit">上传</button>
        <!--预览图片-->
        <div class="preview_box"></div>
    </form>
    <script type="text/javascript">

        $("#img_input").on("change", function (e) {
            var file = e.target.files[0]; //获取图片资源
            // 只选择图片文件
            if (!file.type.match('image.*')) {
                return false;
            }
            var reader = new FileReader();
            reader.readAsDataURL(file); // 读取文件
            // 渲染文件
            reader.onload = function (arg) {

                var img = '<img class="preview" src="' + reader.result + '" alt="preview"/>';
                $(".preview_box").empty().append(img);
            }
        });
    </script>
</body>

在这里插入图片描述

success.html

<body>
<h1>上传成功!</h1>
图片地址为:<span th:text="${url}"></span>
</body>

在这里插入图片描述

springboot使用editormd

editor.md是国人写的markdown开源工具,官网实例在 editor.md
editor.md下载 下载

这是它的一个简单例子
在这里插入图片描述
首先创建工程
在这里插入图片描述
导入相应的依赖

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- 阿里云OSS-->
		<dependency>
			<groupId>com.aliyun.oss</groupId>
			<artifactId>aliyun-sdk-oss</artifactId>
			<version>2.4.0</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

接着引入css和js等相关样式和插件
在这里插入图片描述
创建editor界面

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
    <title>Simple example - Editor.md examples</title>
    <link rel="stylesheet" th:href="@{/css/style.css}"  />
    <link rel="stylesheet" th:href="@{/css/editormd.css}"  />
    <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />
</head>
<body>
<div id="layout">
    <header>
        <h1>Simple example</h1>
    </header>
	
	    <!--form表单包裹,可上传-->
    <form action="/mark/save" method="post">
        <div class="editormd" id="test-editormd">
            <textarea class="editormd-markdown-textarea"  id="content" name="text"></textarea>
        </div>
        <div>
            <input type="submit" value="提交">
        </div>
    </form>
</div>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/editormd.min.js}"></script>
<script type="text/javascript">
    var testEditor;

    $(function() {
        testEditor = editormd("test-editormd", {
            width   : "90%",
            height  : 640,
            syncScrolling : "single",
            path    : "/lib/",
            //开启图片上传
            imageUpload : true,
            //图片上传支持的格式
            imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            //图片上传的路径
            imageUploadURL : "/mark/upload",
            // saveHTMLToTextarea : true
        });
    });
</script>
</body>
</html>

编写controller

  /**
     * 保存markdown源码
     * @param text
     * @return
     */
    @RequestMapping("/save")
    public ModelAndView save(String text){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("markdown",text );
        modelAndView.setViewName("preview");
        System.out.println(text);
        return modelAndView;
    }

    /**
     * 上传本地图片
     * @param file
     * @param model
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public ResponseResult testUpload(@RequestParam("editormd-image-file")MultipartFile file, Model model){
        logger.info("文件上传");
        ResponseResult responseResult = new ResponseResult();
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        try {
            if(file != null){
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream outputStream = new FileOutputStream(newFile);
                    outputStream.write(file.getBytes());
                    outputStream.close();
                    file.transferTo(newFile);
                    String url = aliyunOssUtil.upLoad(newFile);
                    responseResult.setSuccess(1);
                    responseResult.setUrl(url);
                    responseResult.setMessage("上传成功");
                }
            }
        } catch (FileNotFoundException e) {
            responseResult.setSuccess(0);
            responseResult.setMessage("上传失败");
            e.printStackTrace();
        } catch (IOException e) {
            responseResult.setSuccess(0);
            responseResult.setMessage("上传失败");
            e.printStackTrace();
        }
        return responseResult;
    }

图片上传返回的JSON数据必须为如下格式

{
    success : 0 | 1,           // 0 表示上传失败,1 表示上传成功
    message : "提示的信息,上传成功或上传失败及错误信息等。",
    url     : "图片地址"        // 上传成功时才返回
}

在这里插入图片描述

将markdown转换成html并展示

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--css-->
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <link rel="stylesheet" th:href="@{/css/editormd.preview.css}">
    <!--js-->
    <script th:src="@{/js/jquery.min.js}"></script>
    <script th:src="@{/js/marked.min.js}"></script>
    <script th:src="@{/js/prettify.min.js}"></script>
    <script th:src="@{/js/raphael.min.js}"></script>
    <script th:src="@{/js/underscore.min.js}"></script>
    <script th:src="@{/js/sequence-diagram.min.js}"></script>
    <script th:src="@{/js/flowchart.min.js}"></script>
    <script th:src="@{/js/jquery.flowchart.min.js}"></script>
    <script th:src="@{/js/editormd.js}"></script>
</head>
<body>
    <div id="markdown-to-html" class="markdown-body editormd-html-preview" >
        <textarea style="display:none;" name="editormd-markdown-doc" id="mdText" th:text="${markdown}"></textarea>
    </div>
    <script type="text/javascript">
        var markdowntohtml;
        $(function () {
            markdowntohtml = editormd.markdownToHTML("markdown-to-html", {
                htmlDecode: "true", // you can filter tags decode
                emoji: true,
                taskList: true,
                tex: true,
                flowChart: true,
                sequenceDiagram: true
            });
        })
    </script>
</body>
</html>

转换前
在这里插入图片描述
转换后
在这里插入图片描述

完整代码在我的GitHub

发布了65 篇原创文章 · 获赞 74 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_40866897/article/details/95352592