美文网首页
springboot添加ueditor JSP版本 功能

springboot添加ueditor JSP版本 功能

作者: coolfxl | 来源:发表于2019-04-13 16:15 被阅读0次

    1、ueditor官网最新版下载地址: https://ueditor.baidu.com/website/download.html

    [1.4.3.3 Jsp 版本] UTF-8版 2016-02-25

    2、现象: 集成springboot集成JSP版的ueditor时,往往出现以下问题


    配置加载

    分析:1、路径不对 2、加载文件读取失败
    解决:寻找路径配置文件,ueditor.config.js

     //为编辑器实例添加一个路径,这个不能被注释
            UEDITOR_HOME_URL: URL
    
            // 服务器统一请求接口路径
            , serverUrl: URL + "jsp/controller.jsp"
    
            //工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的重新定义
    

    作用:该配置的目的是让serverUrl访问到controller.jsp页面

    
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        import="com.baidu.ueditor.ActionEnter"
        pageEncoding="UTF-8"%>
    <%@ page trimDirectiveWhitespaces="true" %>
    <%
    
        request.setCharacterEncoding( "utf-8" );
        response.setHeader("Content-Type" , "text/html");
        
        String rootPath = application.getRealPath( "/" );
        
        out.write( new ActionEnter( request, rootPath ).exec() );
        
    %>
    

    作用:通过controller.jsp页面以及jsp/lib包下面的ueditor-1.1.2.jar来读取并解析config.json文件


    image.png
    /* 前后端通信相关的配置,注释只允许使用多行方式 */
    {
        /* 上传图片配置项 */
        "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
        "imageFieldName": "upfile", /* 提交的图片表单名称 */
        "imageMaxSize": 2048000, /* 上传大小限制,单位B */
        "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
        "imageCompressEnable": true, /* 是否压缩图片,默认是true */
        "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
        "imageInsertAlign": "none", /* 插入的图片浮动方式 */
        "imageUrlPrefix": "", /* 图片访问路径前缀 */
    

    3、解决:只要通过合理的访问路径解析到config.json文件就可以让文件上传功能正常使用
    4、搭建springboot开发环境,前端框架使用jasper
    可以在 start.spring.io 这个网址创建一个web工程


    创建工程

    解压导入到idea中,新建工程目录、类,解压ueditor到对应目录结构中如下图所示


    工程结构

    5、修改pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.20.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.cool.demo</groupId>
        <artifactId>cool-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <name>cool-demo</name>
        <description>Demo project for Spring Boot with ueditor</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <!-- <scope>provided</scope>-->
            </dependency>
    
            <!--UEditor的依赖 -->
            <dependency>
                <groupId>org.json</groupId>
                <artifactId>json</artifactId>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.2</version>
            </dependency>
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>1.9</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    6、针对读取config.json文件编写对应代码,首先将config.json写成后端路径访问模式

    package com.cool.demo.vo;
    
    /**
     * Created by admin on 2019/4/13.
     */
    public class PublicMsg {
        public final static String UEDITOR_CONFIG = "{\n" +
                "    \"imageActionName\": \"uploadimage\",\n" +
                "    \"imageFieldName\": \"upfile\",\n" +
                "    \"imageMaxSize\": 2048000,\n" +
                "    \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "    \"imageCompressEnable\": true,\n" +
                "    \"imageCompressBorder\": 1600,\n" +
                "    \"imageInsertAlign\": \"none\",\n" +
                "    \"imageUrlPrefix\": \"\",\n" +
                "    \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "\n" +
                "    \"scrawlActionName\": \"uploadscrawl\",\n" +
                "    \"scrawlFieldName\": \"upfile\",\n" +
                "    \"scrawlPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"scrawlMaxSize\": 2048000,\n" +
                "    \"scrawlUrlPrefix\": \"\",\n" +
                "    \"scrawlInsertAlign\": \"none\",\n" +
                "\n" +
                "    \"snapscreenActionName\": \"uploadimage\",\n" +
                "    \"snapscreenPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"snapscreenUrlPrefix\": \"\",\n" +
                "    \"snapscreenInsertAlign\": \"none\",\n" +
                "\n" +
                "    \"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +
                "    \"catcherActionName\": \"catchimage\",\n" +
                "    \"catcherFieldName\": \"source\",\n" +
                "    \"catcherPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"catcherUrlPrefix\": \"\",\n" +
                "    \"catcherMaxSize\": 2048000,\n" +
                "    \"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "\n" +
                "    \"videoActionName\": \"uploadvideo\",\n" +
                "    \"videoFieldName\": \"upfile\",\n" +
                "    \"videoPathFormat\": \"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"videoUrlPrefix\": \"\",\n" +
                "    \"videoMaxSize\": 102400000,\n" +
                "    \"videoAllowFiles\": [\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"],\n" +
                "\n" +
                "    \"fileActionName\": \"uploadfile\",\n" +
                "    \"fileFieldName\": \"upfile\",\n" +
                "    \"filePathFormat\": \"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"fileUrlPrefix\": \"\",\n" +
                "    \"fileMaxSize\": 51200000,\n" +
                "    \"fileAllowFiles\": [\n" +
                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                "    ],\n" +
                "\n" +
                "    \"imageManagerActionName\": \"listimage\",\n" +
                "    \"imageManagerListPath\": \"/ueditor/jsp/upload/image/\",\n" +
                "    \"imageManagerListSize\": 20,\n" +
                "    \"imageManagerUrlPrefix\": \"\",\n" +
                "    \"imageManagerInsertAlign\": \"none\",\n" +
                "    \"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "\n" +
                "    \"fileManagerActionName\": \"listfile\",\n" +
                "    \"fileManagerListPath\": \"/ueditor/jsp/upload/file/\",\n" +
                "    \"fileManagerUrlPrefix\": \"\",\n" +
                "    \"fileManagerListSize\": 20,\n" +
                "    \"fileManagerAllowFiles\": [\n" +
                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                "    ] \n" +
                "\n" +
                "}";
    
    

    7、编写访问路径UeditorController.java,包含返回config.json配置信息,以及文件上传功能

    package com.cool.demo.cooldemo;
    
    import com.cool.demo.vo.PublicMsg;
    import org.apache.commons.io.FilenameUtils;
    import org.apache.commons.io.output.StringBuilderWriter;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.ResourceUtils;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.io.File;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * Created by admin on 2019/4/13.
     */
    @Controller
    public class UeditorController {
    
        /**
         * 替换ueditor jsp/controller.jsp文件
         * 由于controller.jsp + lib下面的ueditor-1.1.2.jar的作用是读取config.json文件,所以这里直接将config.json文件以字符串的形式返回给了前端
         * @param request
         * @return
         */
        @RequestMapping(value = "/ueditor")
        @ResponseBody
        public String ueditor(HttpServletRequest request) {
            return PublicMsg.UEDITOR_CONFIG;
        }
    
        private static final String STORE_PATH = "/image/upload/";
        private static final String SERVER_PATH = "http://localhost:8080";
    
        @RequestMapping(value = "/imgUpload")
        @ResponseBody
        public Map<String, Object> imgUpload(HttpServletRequest request,HttpSession session) {
            Map<String, Object> rs = new HashMap<String, Object>();
            MultipartHttpServletRequest mReq = null;
            MultipartFile file = null;
            String fileName = "";
            String originalFileName = "";
    
            try {
                mReq = (MultipartHttpServletRequest) request;
                // 从config.json中取得上传文件的ID "imageFieldName": "upfile", /* 提交的图片表单名称 */
                file = mReq.getFile("upfile");
    
                if (!file.isEmpty()) {
                    // 取得文件的原始文件名称
                    originalFileName = file.getOriginalFilename();
                    fileName = originalFileName;
    
                    // 设置上传目录
                    String ext = (FilenameUtils.getExtension(file.getOriginalFilename())).toLowerCase();
                    String storePath = "";
                    if ("jpg".equals(ext) || "png".equals(ext) || "jpeg".equals(ext) || "bmp".equals(ext)) {
                        storePath = STORE_PATH;
                    } else {
                        storePath = STORE_PATH;
                    }
    
                    //获取服务器根目录
                    File path = new File("");
                    // 编辑上传目录,使其生效
                    File uploadPath = new File(session.getServletContext().getRealPath("/"),storePath);
    
                    //获取上传的图片具体路径
                    File targetFile = new File(uploadPath, fileName);
    
                    //获取父目录
                    File pfile = new File(uploadPath.getAbsolutePath());
    
                    //判断如果目录不存在,先创建
                    if(!pfile.exists())pfile.mkdirs();
    
                    // 文件上传
                    file.transferTo(targetFile);
    
                    rs.put("state", "SUCCESS"); // UEDITOR的规则:不为SUCCESS则显示state的内容
                    rs.put("url",SERVER_PATH + STORE_PATH + fileName); //能访问到你现在图片的路径
                    rs.put("title", originalFileName);
                    rs.put("original", originalFileName);
                }
            } catch (Exception e) {
                e.printStackTrace();
                rs.put("state", "文件上传失败!"); //在此处写上错误提示信息,这样当错误的时候就会显示此信息
                rs.put("url", "");
                rs.put("title", "");
                rs.put("original", "");
            }
            return rs;
    
        }
    }
    
    

    8、修改ueditor.config.js,访问ueditor解析config.json

    window.UEDITOR_CONFIG = {
    
            //为编辑器实例添加一个路径,这个不能被注释
            UEDITOR_HOME_URL: URL
    
            // 服务器统一请求接口路径
            , serverUrl: "/ueditor"     // "ueditor" // 这个路径也是可以的
    

    9、ueditor解压后全部放置在webapp/ueditor下,具体参考上面图片;将index.html内容拷贝到index.jsp中,修改以下引用文件的路径src="/ueditor/ueditor.config.js",并添加以下内容

    <head>
        <title>完整demo</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
        <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
        <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"> </script>
        <!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
        <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
        <script type="text/javascript" charset="utf-8" src="/ueditor/lang/zh-cn/zh-cn.js"></script>
    
        <style type="text/css">
            div{
                width:100%;
            }
        </style>
    </head>
    
    <script type="text/javascript">
      // 文件上传配置
        UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
        UE.Editor.prototype.getActionUrl = function(action) {
            if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
                return 'http://localhost:8080/imgUpload';
                //'http://localhost:8080/imgUpload';为方法imgUpload的访问地址
            } else {
                return this._bkGetActionUrl.call(this, action);
            }
        }
    </script>
    

    10、至此ueditor部分整合完毕,接着配置web项目,在application.properties添加如下内容

    spring.mvc.view.prefix=/WEB-INF/views/
    spring.mvc.view.suffix=.jsp
    

    11、启动CoolDemoApplication.java,浏览器访问
    http://localhost:8080/index
    查看整个流程

    成功上传界面
    正常显示
    总结:基本上,jsp/lib目录下的文件可以不用,因为相应的jar包在pom.xml中导入了;其中的ueditor-1.1.2.jar和controller.jsp改为了后端读取
    13、附上对应代码,详见gitee,文件上传功能均可用
    https://gitee.com/coolfxl/springboot-jsp-ueditor

    相关文章

      网友评论

          本文标题:springboot添加ueditor JSP版本 功能

          本文链接:https://www.haomeiwen.com/subject/slcrwqtx.html