网站文章内容编辑器(发布文章功能里面最重要的editor需要集成富文本编辑器)

优采云 发布时间: 2021-10-31 00:13

  网站文章内容编辑器(发布文章功能里面最重要的editor需要集成富文本编辑器)

  发布文章功能最重要的部分是需要集成富文本编辑器。目前有很多富文本编辑器,比如ueditor、CKEditor、editor.md等,这里是手表博客中集成的editor.md,因为editor.md是markdown格式。目前,markdown因其简单易用,被广泛应用于各种云笔记、github等。

  1、集成 editor.md

  editor.md在github上开源,开源地址为:,下载最新发布的版本,即:

  

  001.png

  解压后,在系统中添加对应的文章,即:

  

  002.png

  docs、examples 和 tests 文件夹被删除,因为这些文件夹中的文件不需要。

  页面上需要引用的文件如下:

  页面只需要导入editor.md中的editormd.min.css和editormd.min.js文件(注意:对jquery的引用是提前引用的)。

  页面中需要插入富文本编辑器的代码如下:

  注意标签中有一个article-editormd的id值,后面初始化富文本编辑器时需要。

  初始化富文本编辑器的代码如下:

  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"

});

});

  注意:

  最终的富文本编辑器页面效果如下:

  

  003.png

  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 configCache;

@Override

public Object upload(MultipartFile file, String distType, String userId) throws Exception {

Map result = new HashMap();

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 params = new HashMap();

params.put("creator", user.getUserId());

params.put("status", Group.STATUS_SUCCESS);

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

model.addAttribute("user", user);

model.addAttribute("groups", groups);

return Const.BASE_INDEX_PAGE + "blog/article/add";

}

  处理release文章的核心代码是:

  /**

* 新增文章

*

* @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;

}

  完整发布文章页面如下:

  

  004.png

  跟我来

  以您最方便的方式关注我:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线