KindEditor富文本框编辑器上传图片功能实现,基于java项目
Posted 美宰可
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了KindEditor富文本框编辑器上传图片功能实现,基于java项目相关的知识,希望对你有一定的参考价值。
1. HTML标签与jquery代码
<textarea id="editor_id" style="width: 200px; height: 200px;"></textarea>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../kindeditor4.1.11/kindeditor-all.js"></script>
<script type="text/javascript" src="../kindeditor/kindeditor4.1.11/lang/zh-CN.js"></script>
<script type="text/javascript">
// 编辑富文本框
KindEditor.ready(function(K) {
var editor = K.create(‘#editor_id‘, {
themeType : "simple",
uploadJson : CONTEXT_PATH + "transportations/describe/upload",
resizeType : 1,
imageTabIndex : 1,
filterMode : true,
allowPreviewEmoticons : false,
allowImageUpload : true,
allowFileManager : true,
afterBlur : function() {
this.sync();
},
afterUpload : function(url) {
//上传图片后的代码
var image = "<img src=‘"+url+"‘/>";
inserthtmlAtCaret(image);
},
items : [ ‘source‘, ‘undo‘, ‘redo‘, ‘plainpaste‘, ‘wordpaste‘, ‘clearhtml‘, ‘quickformat‘, ‘selectall‘, ‘fullscreen‘, ‘fontname‘, ‘fontsize‘, ‘|‘, ‘forecolor‘,
‘hilitecolor‘, ‘bold‘, ‘italic‘, ‘underline‘, ‘hr‘, ‘removeformat‘, ‘|‘, ‘justifyleft‘, ‘justifycenter‘, ‘justifyright‘, ‘insertorderedlist‘,
‘insertunorderedlist‘, ‘|‘, ‘link‘, ‘image‘, ‘unlink‘, ‘baidumap‘, ‘emoticons‘ ]
});
});
// 在光标处添加内容
function insertHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("textarea");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
document.selection.createRange().pasteHTML(html);
}
}
</script>
2. java后台实现
/**
*
* 富文本框编辑-上传图片
*
* @param localUrl
* @return
* @throws IOException
* @throws FileUploadException
*/
@RequestMapping(value = "upload")
public void uploadImg(HttpServletRequest request, HttpServletResponse response)
{
// 设置Response响应的编码
response.setContentType("text/html; charset=UTF-8");
// 获取一个Response的Write对象
PrintWriter writer = null;
try
{
writer = response.getWriter();
// 文件保存目录路径
String savePath = request.getServletContext().getRealPath("/") + "attached/";
// 文件保存目录URL
String saveUrl = request.getContextPath() + "/attached/";
// 定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
// 最大文件大小
long maxSize = 1000000;
// 判断是否是一个文件
if (!ServletFileUpload.isMultipartContent(request))
{
writer.println(getError("请选择文件。"));
return;
}
// 检查目录upload, 没有则创建一个
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory())
{
uploadDir.mkdirs();
}
// 检查目录写权限
if (!uploadDir.canWrite())
{
writer.println(getError("上传目录没有写权限。"));
return;
}
String dirName = request.getParameter("dir");
if (dirName == null)
{
dirName = "image";
}
if (!extMap.containsKey(dirName))
{
writer.println(getError("目录名不正确。"));
return;
}
// 创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists())
{
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists())
{
dirFile.mkdirs();
}
DefaultMultipartHttpServletRequest servletRequest = (DefaultMultipartHttpServletRequest) request;
Iterator<String> iterator = servletRequest.getFileNames();
while (iterator.hasNext())
{
MultipartFile file = servletRequest.getFile(iterator.next());
String fileName = file.getOriginalFilename();
// 检查文件大小
if (file.getSize() > maxSize)
{
writer.println(getError("上传文件大小超过限制。"));
return;
}
// 检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt))
{
writer.println(getError("上传文件扩展名是不允许的扩展名。
只允许" + extMap.get(dirName) + "格式。"));
return;
}
// 以时间重新命名文件名
String newFileName = CommonUtils.newFileName(fileName);
File uploadedFile = new File(savePath, newFileName);
file.transferTo(uploadedFile);
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", saveUrl + newFileName);
writer.println(obj.toJSONString());
}
}
catch (Exception e)
{
logger.error("上传文件失败!" + e.getMessage());
}
finally
{
// 将writer对象中的内容输出
writer.flush();
// 关闭writer对象
writer.close();
}
}
/**
*
* 上传图片-响应错误信息
*
* @author 戴飞
* @param message
* @return
*/
private String getError(String message)
{
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
return obj.toJSONString();
}
关于KindEditor编辑器,了解更多请参考官网文档;
以上是关于KindEditor富文本框编辑器上传图片功能实现,基于java项目的主要内容,如果未能解决你的问题,请参考以下文章
富文本框插件KindEditor 上传图片不走后台直接js上传文件到oss要怎么处理?