ckeditor如何在服务器端保存图像

时间:2016-10-04 06:38:29

标签: spring-mvc ckeditor image-uploading

我在网上使用ckeditor,想要用图像编辑一些章节,但我发现很难用ckeditor从本地计算机上传图像。我参考此示例ckeditor upload image,我的问题是当我点击send it to server标签上的upload按钮时,如何获取图像文件。我也不知道如何在send it to server成功后返回图片网址。

我在服务器端使用spring boot spring mvc和hibernate。我希望任何人都可以帮我发布服务器端的源代码,或者只是给一些相关材料也好。

1 个答案:

答案 0 :(得分:2)

它非常容易实现,让我们看看...

javascript代码::

<script>
        $(document).ready(function () {
            CKEDITOR.replace('editor', {
                filebrowserImageUploadUrl: '/image/upload'
            });
            CKEDITOR.on('dialogDefinition', function (e) {
                var dialogName = e.data.name;
                var dialogDefinition = e.data.definition;
                switch (dialogName) {
                    case  'image':
                        //dialogDefinition.removeContents('info');
                        dialogDefinition.removeContents('Link');
                        // dialogDefinition.removeContents('advanced');
                        break;
                }
            });
            $('#btn_publish').click(function () {
                alert(CKEDITOR.instances.editor.getData());
            });
            $('#btn_clear').click(function () {
                CKEDITOR.instances.editor.setData('');
            });
        });
    </script>

html代码::

<form method="post" action="#" th:action="@{/abc}" th:object="${abc}"
              enctype="multipart/form-data">
<textarea name="cont" id="editor" rows="10" cols="80" th:field="*{newsDescription}"></textarea>
            <button type="button" id="btn_publish">Show</button>
            <button type="button" id="btn_clear">Clear All</button>
            <input type="submit" value="submit">
        </form>

然后转到spring java类,它看起来像:

@PostMapping("/image/upload")
public String upload(@RequestPart MultipartFile upload, @RequestParam(value = "CKEditorFuncNum") String callback, HttpServletRequest request) throws IOException {
    System.out.println(upload.getOriginalFilename());
    String sourceName = upload.getOriginalFilename();
    String sourceExt = FilenameUtils.getExtension(sourceName);
    File destFile;
    String destFileName;
    do {
        destFileName = RandomStringUtils.randomAlphabetic(8).concat(".").concat(sourceExt);
        destFile = new File(uploadPath.concat(destFileName));
    } while (destFile.exists());
    destFile.getParentFile().mkdirs();
    upload.transferTo(destFile);
    String imgUrl = request.getScheme().concat("://").concat(request.getServerName()).concat(":").concat(String.valueOf(request.getServerPort())).concat(uploadUri).concat(destFileName);
    StringBuffer sb = new StringBuffer();
    sb.append("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(");
    sb.append(callback);
    sb.append(",'");
    sb.append(imgUrl);
    sb.append("','image uploaded successfully!!')</script>");
    return sb.toString();
}