• Spring boot 集成ckeditor


    1:下载ckeditor  4.4.2 full package ,官网没有显示, 需要在最新版本的ckeditor download右键,复制链接, 输入到导航栏,将版本号改为自己想要的版本号。

         https://download.cksource.com/CKEditor/CKEditor/CKEditor%204.4.2/ckeditor_4.4.2_full.zip

    2:修改  config.js,加载图片上传  插件

         

    /**
     * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
     * For licensing, see LICENSE.html or http://ckeditor.com/license
     */
    
    CKEDITOR.editorConfig = function( config ) {
        // Define changes to default configuration here. For example:
        // config.language = 'fr';
        // config.uiColor = '#AADC6E';
            // Define changes to default configuration here.
        // For complete reference see:
        // http://docs.ckeditor.com/#!/api/CKEDITOR.config
    
        // The toolbar groups arrangement, optimized for two toolbar rows.
        config.toolbarGroups = [
            { name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
            { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
            { name: 'links' },
            { name: 'insert' },
            { name: 'forms' },
            { name: 'tools' },
            { name: 'document',       groups: [ 'mode', 'document', 'doctools' ] },
            { name: 'others' },
            '/',
            { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
            { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
            { name: 'styles' },
            { name: 'colors' },
            { name: 'about' }
        ];
    
        // Remove some buttons provided by the standard plugins, which are
        // not needed in the Standard(s) toolbar.
        config.removeButtons = 'Underline,Subscript,Superscript';
    
        // Set the most common block elements.
        config.format_tags = 'p;h1;h2;h3;pre';
    
        // Simplify the dialog windows.
        config.removeDialogTabs = 'image:advanced;link:advanced';
        config.filebrowserImageUploadUrl= '/upload/image';            //上传图片后台接口
    };

    3:index.html   里面引入ckeditor编辑框

          

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>A Simple Page with CKEditor</title>
        <!-- Make sure the path to CKEditor is correct. -->
        <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
        <script type="text/javascript" src="/ckeditor/config.js"></script>
    </head>
    <body>
    <form>
                <textarea name="editor1" id="editor1" rows="10" cols="80">
                    This is my textarea to be replaced with CKEditor.
                </textarea>
                <script>
                    // Replace the <textarea id="editor1"> with a CKEditor
                    // instance, using default configuration.
                    CKEDITOR.replace( 'editor1' );
                </script>
    </form>
    </body>
    </html>

    4:搭建spring boot 框架,提供后台上传 图片接口

          

    @Controller
    public class CKEditorController {
    
        Logger logger = LogManager.getLogger(CKEditorController.class);
    
        @RequestMapping("/")
        public String ckeditor(Model model) {
            System.out.println("进入");
    //        Student student=new Student("AA","1","abcdljaldf");
    //        model.addAttribute("status","Hello");
    //        model.addAttribute("page",student);
            return "/index.html";
        }
    
    
        @Value(value = "${cbs.imagesPath}")  //配置的图片路径
        private String ckeditorStorageImagePath;
    
        @Value(value = "${cbs.imagesPath}")
        private String ckeditorAccessImageUrl;
    
        @RequestMapping(value = "/upload/image", method = RequestMethod.POST)
        @ResponseBody
        public String uploadImage1(@RequestParam("upload") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
            logger.debug("上传");
            String name = "";
            if (!file.isEmpty()) {
                try {
                    response.reset();
    //                response.setContentType("text/html; charset=ISO-8859-1");
                    response.setContentType("text/html;charset=UTF-8");
                    response.setHeader("Cache-Control", "no-cache");
                    //解决跨域问题
                    //Refused to display 'http://localhost:8080/upload/mgmt/img?CKEditor=practice_content&CKEditorFuncNum=1&langCode=zh-cn' in a frame because it set 'X-Frame-Options' to 'DENY'.
                    response.setHeader("X-Frame-Options", "SAMEORIGIN");
                    PrintWriter out = response.getWriter();  // 最新版本的 会提示出错:  getWriter has already exists,
    //                ServletOutputStream out = response.getOutputStream();  
    
                    String fileClientName = file.getOriginalFilename();
                    String pathName = ckeditorStorageImagePath + fileClientName;
                    File newfile = new File(pathName);
                    byte[] bytes = file.getBytes();
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newfile));
                    stream.write(bytes);
                    stream.close();
    
                    // 组装返回url,以便于ckeditor定位图片
                    String fileUrl = ckeditorAccessImageUrl + File.separator + newfile.getName();
    
    
                    // 将上传的图片的url返回给ckeditor
                    String callback = request.getParameter("CKEditorFuncNum");
                    logger.debug("callback"+callback+"fileUrl"+fileUrl);
                    String script = "<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction(" + callback + ", '" + fileUrl + "');</script>";
                    out.println(script);
                    out.flush();
                    out.close();
                } catch (Exception e) {
    //                logger.info("You failed to upload " + name + " => " + e.getMessage());
                    e.printStackTrace();
                }
            } else {
    //            logger.info("You failed to upload " + name + " because the file was empty.");
            }
            return "SUCCESS";
        }

        //加载图片
        @RequestMapping(method = RequestMethod.GET, value = "/displayImage/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {
    System.out.println(filename );
    try {
    // return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(basePath+imagePath, filename).toString()));
    // return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(basePath+imagePath, filename).toString()));
    return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ckeditorStorageImagePath, filename).toString()));
    } catch (Exception e) {
    return ResponseEntity.notFound().build();
    }
    }
    }

    5:前台访问,http://localhost:8080   ,上传图片,返回图片路径成功

  • 相关阅读:
    2.3 Nginx服务的启停控制
    2.1 Nginx服务器安装
    三、函数 (SUM、MIN、MAX、COUNT、AVG)
    二、检索语句 SELECT、ORDER BY、WHERE
    一、数据库、SQL简介
    一、单元测试框架的基本使用介绍
    2.4 Nginx服务器基础配置指令
    第十七章 程序管理与SELinux初探--进程、进程管理(ps、top)
    第十五章 例行性工作(crontab)--循环执行的例行性工作调度 crontab(定时任务)
    java多线程04----------final和static
  • 原文地址:https://www.cnblogs.com/liyafei/p/9193262.html
Copyright © 2020-2023  润新知