基於SpringBoot從零構建博客網站 - 集成editor.md開發發布文章功能


發布文章功能里面最重要的就是需要集成富文本編輯器,目前富文本編輯器有很多,例如ueditor,CKEditor、editor.md等。這里守望博客里面是集成的editor.md,因為editor.md是markdown格式,目前markdown由於簡潔好用,在各種雲筆記、github等中得到了廣泛使用。

1、集成editor.md

editor.md是在github上開源,開源地址為:https://github.com/pandao/editor.md,下載其發布的最新版本,即:

解壓后,將相應的文章添加到系統中,即:

將這些docs、examples、tests文件夾是刪除了的,因為這些文件夾里面的文件是不需要用到的。

頁面中需要引用的文件如下:

<link href="${rc.contextPath}/static/plugins/editor/css/editormd.min.css" rel="stylesheet">
<script src="${rc.contextPath}/static/plugins/editor/editormd.min.js" type="text/javascript"></script>

頁面中只需要引入editor.md中的editormd.min.css和editormd.min.js文件(注意:對於jquery相關的引用是提前就引用好的)。

頁面中需要插入富文本編輯器的地方代碼如下:

<div class="form-group">
    <div class="col-sm-12" id="article-editormd">
        <textarea style="display:none;"></textarea>
    </div>
</div>

注意標簽中有一個id值為article-editormd,后面初始化富文本編輯器時,需要用到。

初始化富文本編輯器的代碼如下:

var editor;
$(function () {
    editor = editormd("article-editormd", {
        width: "100%",
        height: 640,
        placeholder: '',
        syncScrolling: "single",
        path: "${rc.contextPath}/static/plugins/editor/lib/",
        saveHTMLToTextarea: true,
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp"],
        imageUploadURL: "${rc.contextPath}/upload?_distType=_articleImg",
        imageUploadFileName: "_uploadFile",
        toolbarIcons: "sw"
    });
});

注意:

  • 其中imageUploadFileName參數名,是我擴展的,原生的editor.md是沒有這個參數的。擴展這個參數的原因是因為editor.md中對於上傳圖片的文件名為editormd-image-file,由於守望博客中對於上傳模塊進行統一抽象,即上傳名稱統一為_uploadFile,為此就擴展了這個參數進行修改上傳圖片的文件名。

  • 對於toolbarIcons參數的參數值,也是我擴展的,因為原生的editor.md工具欄的種類只有3種,即:full、simple、mini。這樣導致工具欄要么太多了,要么太少了,所以就再定義一個sw,里面工具就是自己想要的工具,即:

    sw : [
        "undo", "redo", "|",
        "bold", "del", "italic", "quote", "|",
        "h1", "h2", "h3", "h4", "h5", "h6", "|",
        "list-ul", "list-ol", "hr", "|",
        "link", "image", "code", "preformatted-text", "code-block", "table", "html-entities", "|",
        "watch", "preview", "clear", "search"
    ]
    

最終富文本編輯器頁面效果如下:

2、開發布文章功能

處理文章圖片的UploadGroupLogoHandler,內容為:

/**
 * 上傳專欄Logo處理類
 *
 * @author lzj
 * @since 1.0
 * @date [2019-07-23]
 */
@Slf4j
@Component("_groupLogo")
public class UploadGroupLogoHandler implements IUploadHandler {

    @Resource(name = "configCache")
    private ICache<Config> configCache;

    @Override
    public Object upload(MultipartFile file, String distType, String userId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            // 獲取圖片的原始名稱
            String originalName = file.getOriginalFilename();

            // 判斷圖片的類型
            if (!(originalName.endsWith(".jpg") || originalName.endsWith(".JPG") || originalName.endsWith(".png") || originalName.endsWith(".PNG") || originalName.endsWith(".gif") || originalName.endsWith(".GIF") || originalName.endsWith(".jpeg") || originalName.endsWith(".JPEG"))) {
                throw new TipException("您上傳的圖片類型有誤,請上傳格式為jpg、png或gif");
            }

            // 獲取圖片的大小
            long fileSize = file.getSize();

            // 圖片大小不能超過2M, 2M = 2 * 1024 * 1024B = 2097152B
            if (fileSize > 2097152L) {
                throw new TipException("您上傳的圖片超過2M");
            }

            Config config = configCache.get(Config.CONFIG_IMG_GROUP_LOGO_PATH);
            // 保存頭像的根目錄
            String basePath = config.getConfigValue();
            if (!(basePath.endsWith("/") || basePath.endsWith("\\"))) {
                basePath += "/";
            }

            // 根據當前時間構建yyyyMM的文件夾,建立到月的文件夾
            String dateDirName = DateUtil.date2Str(new Date(), DateUtil.YEAR_MONTH_FORMAT);
            basePath += dateDirName;

            File imageDir = new File(basePath);
            if (!imageDir.exists()) {
                imageDir.mkdirs();
            }

            String fileNewName = IdGenarator.guid() + originalName.substring(originalName.lastIndexOf("."));
            FileUtil.copy(file.getInputStream(), new FileOutputStream(new File(imageDir, fileNewName)));

            result.put("url", dateDirName + "/" + fileNewName);
            result.put("msg", "上傳成功");
        } catch (TipException e) {
            result.put("url", "");
            result.put("msg", e.getMessage());
        } catch (Exception e) {
            log.error("上傳失敗", e);
            result.put("url", "");
            result.put("msg", "上傳失敗");
        }
        return result;
    }

    @Override
    public void download(String fileId, HttpServletResponse response) throws Exception {
    }

    @Override
    public Object list(String distType, String userId) throws Exception {
        return null;
    }
}

加載出發布文章頁面核心代碼為:

/**
 * 加載出新增文章頁面
 *
 * @param model
 * @param request
 * @param session
 * @return
 */
@RequestMapping(value = "/user/article/add", method = RequestMethod.GET)
public String add(Model model, HttpServletRequest request, HttpSession session) {
    // 獲取登錄信息
    User tempUser = (User) session.getAttribute(Const.SESSION_USER);
    String userId = tempUser.getUserId();

    // 獲取用戶信息
    User user = userService.getById(userId);

    // 構建專欄的查詢條件
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("creator", user.getUserId());
    params.put("status", Group.STATUS_SUCCESS);

    List<Group> groups = groupService.list(new QueryWrapper<Group>().allEq(params).orderByDesc("createTime"));

    model.addAttribute("user", user);
    model.addAttribute("groups", groups);
    return Const.BASE_INDEX_PAGE + "blog/article/add";
}

處理發布文章的核心代碼為:

/**
 * 新增文章
 *
 * @param request
 * @param session
 * @return
 */
@RequestMapping(value = "/user/article/add", method = RequestMethod.POST)
@ResponseBody
public Result add(HttpServletRequest request, HttpSession session) {
    Result result = new Result();
    try {
        // 接收參數
        String groupId = request.getParameter("groupId");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String tag = request.getParameter("tag");
        String description = request.getParameter("description");
        String typeStr = request.getParameter("type");
        String canTopStr = request.getParameter("canTop");
        String canCommentStr = request.getParameter("canComment");

        // 校驗參數
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(content) || StringUtils.isEmpty(description)) {
            throw new TipException("缺少必要參數");
        }

        int type = 0;
        int canTop = 0;
        int canComment = 1;
        try {
            type = Integer.parseInt(typeStr);
            canTop = Integer.parseInt(canTopStr);
            canComment = Integer.parseInt(canCommentStr);
        } catch (Exception e) {
            throw new TipException("參數類型錯誤");
        }

        // 去html相關標簽
        description = StringUtil.replaceHtmlTags(description);

        // 客戶端ip
        String ip = HttpUtil.getIpAddr(request);

        // 獲取session中的用戶信息
        User tempUser = (User) session.getAttribute(Const.SESSION_USER);
        String userId = tempUser.getUserId();

        // 封裝文章信息
        Article article = new Article();
        article.setArticleId(IdGenarator.guid());
        article.setGroupId(groupId);
        article.setTitle(title);
        article.setContent(content);
        article.setDescription(description);
        article.setType(type);
        article.setCanTop(canTop);
        article.setCanComment(canComment);
        article.setViewCount(0L);
        article.setGoodNum(0L);
        article.setBadNum(0L);
        article.setCreateTime(new Date());
        article.setCreateIp(ip);
        article.setUserId(userId);

        // 保存文章
        articleService.create(article, tag);

        result.setCode(Result.CODE_SUCCESS);
        result.setMsg("發布文章成功");
    } catch (TipException e) {
        result.setCode(Result.CODE_EXCEPTION);
        result.setMsg(e.getMessage());
    } catch (Exception e) {
        log.error("新增文章失敗", e);
        result.setCode(Result.CODE_EXCEPTION);
        result.setMsg("新增文章失敗");
    }
    return result;
}

完整的發布文章頁面如下:

關注我

以你最方便的方式關注我:
微信公眾號:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM