Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Integrating CKEditor 4.4.2 with Spring Boot for Image Upload

Tech May 17 1

Downloading CKEditor 4.4.2 Full Package

Since the official download page may default to the latest version, you can obtain the 4.4.2 full package by manually editing the download link:

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

Configuring the Editor for Image Uploads

Edit the config.js file inside the CKEditor folder to enable the file browser upload plugin and set your backend endpoint:

CKEDITOR.editorConfig = function( config ) {
    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' }
    ];
    config.removeButtons = 'Underline,Subscript,Superscript';
    config.format_tags = 'p;h1;h2;h3;pre';
    config.removeDialogTabs = 'image:advanced;link:advanced';
    config.filebrowserImageUploadUrl = '/upload/image';
};

Setting Up the Frontend HTML Page

Create an index.html file that includes the CKEditor script and replaces a textarea with the editor instance:


<html>
<head>
    <meta charset="utf-8">
    <title>Spring Boot CKEditor Demo</title>
    <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
    <script type="text/javascript" src="/ckeditor/config.js"></script>
</head>
<body>
    <form>
        <textarea name="content" id="editor1" rows="10" cols="80">
            This is the textarea to be replaced with CKEditor.
        </textarea>
        <script>
            CKEDITOR.replace( 'editor1' );
        </script>
    </form>
</body>
</html>

Building the Spring Boot Upload Endpoint

Create a controller class that handles image uploads and serves the stored files. The upload endpoint expects a multipart file named upload and returns a JavaScript callback function for CKEditor integration.

@Controller
public class EditorController {
    private static final Logger logger = LogManager.getLogger(EditorController.class);

    @Value("${upload.image.storage.path}")
    private String storagePath;

    @Value("${upload.image.access.url}")
    private String accessUrl;

    @GetMapping("/")
    public String showEditor() {
        return "forward:/index.html";
    }

    @PostMapping("/upload/image")
    @ResponseBody
    public String handleImageUpload(@RequestParam("upload") MultipartFile file,
                                    HttpServletRequest request,
                                    HttpServletResponse response) {
        if (file.isEmpty()) {
            return "NO_FILE";
        }
        try {
            response.reset();
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("X-Frame-Options", "SAMEORIGIN");

            String originalName = file.getOriginalFilename();
            java.nio.file.Path targetPath = Paths.get(storagePath, originalName);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            String fileUrl = accessUrl + "/" + targetPath.getFileName();
            String callback = request.getParameter("CKEditorFuncNum");
            String script = String.format(
                "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(%s, '%s');</script>",
                callback, fileUrl
            );

            response.getWriter().println(script);
            response.getWriter().flush();
        } catch (Exception e) {
            logger.error("Upload failed", e);
            return "FAILURE";
        }
        return null;
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> getFile(@PathVariable String filename) {
        try {
            Path filePath = Paths.get(storagePath, filename);
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return ResponseEntity.ok(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}

Make sure to configure the application.properties with the upload directory and access URL:

upload.image.storage.path=/var/data/images
upload.image.access.url=http://localhost:8080/files

Testing the Integration

Start the Spring Boot application and navigate to http://localhost:8080/. The CKEditor should load, and when you upload an image via the editor toolbar, the image will be saved to the configured path and displayed back in the content area.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.