本博客前面还有一个简化版容易理解:https://blog.csdn.net/Strive279/article/details/121250542
1.自定义编辑器

// 创建编辑器editor = KindEditor.create( "#editor_id", {resizeType : 1,allowImageUpload:true,//允许上传图片allowFileManager:true, //允许对上传图片进行管理uploadJson:root + '/fileUpload',filePostName: 'imgFile',// name属性默认值fileManagerJson:root + '/fileManager',afterChange:function(){this.sync();},afterUpload: function(){this.sync();}, //图片上传后,将上传内容同步到textarea中afterBlur: function(){this.sync();},   失去焦点时,将上传内容同步到textarea中afterCreate : function() { this.sync();   },afterBlur:function(){  this.sync(); },items: ['source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste','plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright','justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript','superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/','formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold','italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image','table', 'hr', 'emoticons', 'baidumap', 'pagebreak','anchor', 'link', 'unlink'],allowFileManager: true});

2.Java实现代码

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;@Controller
public class KindEditorUpload{private String PATH_LINE = "/";/*** 文件上传** @param request  {@link HttpServletRequest}* @param response {@link HttpServletResponse}* @return json response*/@SuppressWarnings("unchecked")@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)@ResponseBodypublic void fileUpload(HttpServletRequest request, HttpServletResponse response,@RequestParam("imgFile") MultipartFile[] imgFile) {try {response.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();// 文件保存本地目录路径String savePath = PathConfig.temporaryFilePath + PathConfig.imgPath;// 文件保存目录URLString saveUrl = request.getContextPath() + "/KindEditor/uploads/";System.out.println("savePath----------------->" + savePath);System.out.println("saveUrl----------------->" + saveUrl);if (!ServletFileUpload.isMultipartContent(request)) {out.print(getError("请选择文件。"));out.close();return;}// 检查目录File uploadDir = new File(savePath);
//            if (!uploadDir.isDirectory()) {//                out.print(getError("上传目录不存在。"));
//                out.close();
//                return;
//            }if (!uploadDir.exists()) { //如果不存在uploadDir.mkdirs(); //创建该文件夹}// 检查目录写权限if (!uploadDir.canWrite()) {out.print(getError("上传目录没有写权限。"));out.close();return;}String dirName = request.getParameter("dir");if (dirName == null) {dirName = "image";}// 定义允许上传的文件扩展名Map<String, String> extMap = new HashMap<String, String>();extMap.put("image", "gif,jpg,jpeg,png,bmp");extMap.put("flash", "swf,flv");extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,xml,txt,zip,rar,gz,bz2");if (!extMap.containsKey(dirName)) {out.print(getError("目录名不正确。"));out.close();return;}// 创建文件夹
//            savePath += dirName + PATH_LINE;
//            saveUrl += dirName + PATH_LINE;File saveDirFile = new File(savePath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}//             //最大文件大小
//              long maxSize = 1000000;// 保存文件for (MultipartFile iFile : imgFile) {String fileName = iFile.getOriginalFilename();//                   //检查文件大小
//                  if(iFile.getSize() > maxSize){//                      out.print(getError("上传文件大小超过限制。"));
//                      out.close();
//                      return;
//                  }// 检查扩展名String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {// return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");out.print(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));out.close();return;}SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;try {File uploadedFile = new File(savePath, newFileName);// 写入文件FileUtils.copyInputStreamToFile(iFile.getInputStream(), uploadedFile);} catch (Exception e) {out.print(getError("上传文件失败。"));out.close();return;}JSONObject obj = new JSONObject();obj.put("error", 0);
//                obj.put("url", request.getServletContext().getRealPath(saveUrl) + newFileName);obj.put("url", "/showImg?imgUrl=" + newFileName);out.print(obj.toJSONString());out.close();}} catch (Exception e) {e.printStackTrace();}}private Map<String, Object> getError(String errorMsg) {Map<String, Object> errorMap = new HashMap<String, Object>();errorMap.put("error", 1);errorMap.put("message", errorMsg);return errorMap;}/*** @param imgUrl 图片在本地磁盘的位置 如:E:/teacherCompetition/1/images/1.jpg* @param request* @param response*/@RequestMapping("/showImg")public void picToJSP(@RequestParam("imgUrl") String imgUrl, HttpServletRequest request, HttpServletResponse response){FileInputStream in;response.setContentType("application/octet-stream;charset=UTF-8");try {//图片读取路径String basePath = PathConfig.temporaryFilePath + PathConfig.imgPath;File file=new File(basePath + imgUrl);if(!file.exists()){String pattern = "^file:[/]*";imgUrl = imgUrl.replaceAll(pattern, "");in=new FileInputStream(imgUrl);} else {in=new FileInputStream(basePath + imgUrl);}int i=in.available();byte[]data=new byte[i];in.read(data);in.close();//写图片OutputStream outputStream=new BufferedOutputStream(response.getOutputStream());outputStream.write(data);outputStream.flush();outputStream.close();} catch (Exception e) {e.printStackTrace();}}/*** 文件空间** @param request  {@link HttpServletRequest}* @param response {@link HttpServletResponse}* @return json*/@SuppressWarnings("unchecked")@RequestMapping(value = "/fileManager")@ResponseBodypublic void fileManager(HttpServletRequest request, HttpServletResponse response) {try {// 根目录路径,可以指定绝对路径String rootPath = PathConfig.temporaryFilePath + PathConfig.imgPath;// 根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/String rootUrl = PathConfig.temporaryFilePath + "/showImg?imgUrl=";System.out.println("rootPath----------------->" + rootPath);System.out.println("rootUrl----------------->" + rootUrl);response.setContentType("application/json; charset=UTF-8");PrintWriter out = response.getWriter();// 图片扩展名String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };String dirName = request.getParameter("dir");if (dirName != null) {if (!Arrays.<String>asList(new String[] { "image", "flash", "media", "file" }).contains(dirName)) {out.print("无效的文件夹。");out.close();return;}
//                rootPath += dirName + PATH_LINE;
//                rootUrl += PATH_LINE;File saveDirFile = new File(rootPath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}}// 根据path参数,设置各路径和URLString path = request.getParameter("path") != null ? request.getParameter("path") : "";String currentPath = rootPath + path;String currentUrl = rootUrl + path;String currentDirPath = path;String moveupDirPath = "";if (!"".equals(path)) {String str = currentDirPath.substring(0, currentDirPath.length() - 1);moveupDirPath = str.lastIndexOf(PATH_LINE) >= 0 ? str.substring(0, str.lastIndexOf(PATH_LINE) + 1) : "";}// 排序形式,name or size or typeString order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";// 不允许使用..移动到上一级目录if (path.indexOf("..") >= 0) {out.print("访问权限拒绝。");out.close();return;}// 最后一个字符不是/if (!"".equals(path) && !path.endsWith(PATH_LINE)) {out.print("无效的访问参数验证。");out.close();return;}// 目录不存在或不是目录File currentPathFile = new File(currentPath);if (!currentPathFile.isDirectory()) {out.print("文件夹不存在。");out.close();return;}// 遍历目录取的文件信息List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();if (currentPathFile.listFiles() != null) {for (File file : currentPathFile.listFiles()) {Hashtable<String, Object> hash = new Hashtable<String, Object>();String fileName = file.getName();if (file.isDirectory()) {hash.put("is_dir", true);hash.put("has_file", (file.listFiles() != null));hash.put("filesize", 0L);hash.put("is_photo", false);hash.put("filetype", "");} else if (file.isFile()) {String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();hash.put("is_dir", false);hash.put("has_file", false);hash.put("filesize", file.length());hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));hash.put("filetype", fileExt);}hash.put("filename", fileName);hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));fileList.add(hash);}}if ("size".equals(order)) {Collections.sort(fileList, new SizeComparator());} else if ("type".equals(order)) {Collections.sort(fileList, new TypeComparator());} else {Collections.sort(fileList, new NameComparator());}JSONObject result = new JSONObject();result.put("moveup_dir_path", moveupDirPath);result.put("current_dir_path", currentDirPath);result.put("current_url", currentUrl);result.put("total_count", fileList.size());result.put("file_list", fileList);out.println(result.toJSONString());out.close();} catch (IOException e) {e.printStackTrace();}}

pathConfig配置文件

package com.newdo.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component
public class PathConfig {/**路径类型*/public static String pathType;@Value(value="${path.type}")public void setSavePath(String savePath){pathType = savePath;}/**临时文件存储目录*/public static String temporaryFilePath;@Value(value="${temporary.filePath}")public void setSavePath1(String savePath){temporaryFilePath = savePath;}/**临时文件存储后续目录*/public static String temporaryPath;@Value(value="${temporary.Path}")public void setSavePath2(String savePath){temporaryPath = savePath;}/**图片存储目录*/public static String imgPath;@Value(value="${img.Path}")public void setSavePath3(String savePath){imgPath = savePath;}
}

application配置文件需要添加的参数

#静态资源
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/#设置请求大小限制
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB#路径类型 windows:\\  liunx:/
path.type=\\
#path.type=/#临时文件存放路径
temporary.filePath=D:\\dxproject\\temporaryFile
temporary.Path=\\resources\\temporaryFile\\
#temporary.filePath=/usr/zhgxrsgl-tomcat
#temporary.Path=/resources/temporaryFile/#图片存放路径
img.Path=\\KindEditor\\uploads\\
#img.Path=/KindEditor/uploads/

KindEditor实现上传图片与回显相关推荐

  1. 【java】批量上传图片并回显功能

    一.前言 在电商的网站中,图片上传功能必不可少,小编在最近的项目中就有遇到了一个批量上传图片并且要回显的功能.可以说这是一个很常见的功能了,已经烂大街了,但是小编还是要认真的分析一下,以便日后用到. ...

  2. java上传图片回显_【java】批量上传图片并回显功能

    一.前言 在电商的网站中,图片上传功能必不可少,小编在最近的项目中就有遇到了一个批量上传图片并且要回显的功能.可以说这是一个很常见的功能了,已经烂大街了,但是小编还是要认真的分析一下,以便日后用到. ...

  3. java spring 上传图片,springboot 上传图片并回显

    之前也有做过上传图片的功能,不过是用在ssm的项目中,也有很多的不完美. 这次用的springboot,基本上对上传图片又有了一定的认识,想再这里记录一下./** * 上传图片 * * @return ...

  4. springboot 上传图片并回显

    之前也有做过上传图片的功能,不过是用在ssm的项目中,也有很多的不完美. 这次用的springboot,基本上对上传图片又有了一定的认识,想再这里记录一下. /*** 上传图片** @return*/ ...

  5. 使用Dropzone上传图片及回显示例

    一.图片上传所涉及到的问题 1.HTML页面中引入这么一段代码 <div class="row"><div class="col-md-12" ...

  6. 解决微信小程序上传图片不能回显的问题

    后台处理要正确 首先要保证后台采用根据系统自动识别的方法返回地址分隔符 (File.separator) 系统不同,结果不同. 按上述所说,后台根据系统自动识别,那么Linux系统将不会出现问题,返回 ...

  7. HTML上传图片的回显

    document.getElementById("showImg").src = window.URL.createObjectURL(personsFile.files[0]); ...

  8. Ajax简单异步上传图片并回显

    前台代码 上传图片按钮 <a href="javascript:void(0)" onclick="uploadPhoto()">选择图片</ ...

  9. 详细记录Word文档(包含doc文件和docx文件的上传图片会回显)转Html实现前端预览

    实现了两种格式Word文档转Html的需求 优点:可以实现多图的doc文档和docx文档转HTML代码,图片也会完美展示,图片不需要保存到本地服务器,直接上传到文件服务器即可,文档格式也会保留 缺点: ...

  10. 小程序上传图片、回显、并上传到服务器

     wx.chooseImage是获取图片,一个是 wx.uploadFile是上传图片 //选取图片 wx.chooseImage({count: 1,sizeType: ['original'],/ ...

最新文章

  1. 记录Docker in Docker 安装(CentOS7)
  2. Android之如何解决android.os.NetworkOnMainThreadException的异常
  3. Java总结:SpringBoot的使用cmd命令进行Gradle构建
  4. 【转】HTTP响应报文与工作原理详解
  5. SQL Server 2005 应用 全文搜索
  6. bilibili弹幕下载方法
  7. python学习手册第五版_自学笔记系列:《Python学习手册 第五版》 -写在开始之前...
  8. python+matplotlib对柿子图的彩色和灰色直方图统计
  9. 响应式极简新闻发布系统源码
  10. Ceph使用---块设备、RGW、CephFS初步使用
  11. 计算机教师幽默介绍,老师幽默的自我介绍6篇
  12. Linux 查看文件和文件夹大小,隐藏文件的大小方法总结
  13. 国庆荐书 | 2020年3季度我读过的十本好书!
  14. windows中添加一个网络位置与映射网络驱动器的区别
  15. 写给Java架构师的一封信(内附架构学习路线)
  16. 如何清理hue元数据库里面的历史数据
  17. mysql数据库内连接、左连接、右连接的区别
  18. 【python之操作注册表】Python删除注册表节点下的值
  19. AUTOSAR NvM 基础篇(三)
  20. a类学科计算机,上海交通大学a类学科有哪些?附上海交大a类学科名单

热门文章

  1. DM数据库归档备份还原
  2. Java Spring Security 安全框架:(四)PasswordEncoder 密码解析器详解
  3. IDEA 插件开发 - 创建自定义私有仓库
  4. WordPress去掉分类链接中category目录的两种方法
  5. ARM Keil5下载安装并导入STM32芯片
  6. linux img工具,线刷包img提取工具(simg2img win)
  7. springboot配置错误页面
  8. QCC3020 单地址量产项目 功耗数据 电流测试数据
  9. 基于springboot高校社团管理系统
  10. requests库及相关知识点(get,post区别,params与data区别)