spring mvc引入百度编辑器ueditor及遇到的问题和解决方法

 

1:下载编辑器源码,下载地址:http://ueditor.baidu.com/website/download.html#ueditor

2:将下载的文件夹解压到ueditor

3: 将ueditor复制到工程plugins目录下,目录结构为:webapp/plugins/ueditor

4: 将需要显示百度编辑器的html文件中加入下面代码

<!-- 配置文件 -->
<script type="text/javascript" src="${ctx}/plugins/ueditor/ueditor.config.js"></script>
<!-- 编辑器源码文件 -->
<script type="text/javascript" src="${ctx}/plugins/ueditor/ueditor.all.js"></script>
<script
src="${ctx}/libs/js/jquery-3.2.1.min.js"></script>

 

<script type="text/javascript">

    var ue = UE.getEditor('container');
</script>

 

其中container是加载编辑器容器的id值,例如:

<!-- 加载编辑器的容器 -->

<div id="container">



</div>

 

5:编辑Controller接口代码,具体相关代码如下

@Controller

@RequestMapping("/ued")

public class UEditorController {



    @Value("${picvediourl}")

    private String picVideoStorageUrl;



    @RequestMapping(value = "/config")

    @ResponseBody

    public Object config(HttpServletRequest request,

                         @RequestParam(value = "action") String action

    ) throws Exception {



        switch (action) {

            case "config":

                return getConfig();

            case "uploadvideo": // 上传视频

            case "uploadimage": // 上传图片

                if (request instanceof MultipartHttpServletRequest) {

                    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;

                    MultipartFile multipartFile = multipartHttpServletRequest.getFile("upfile");

                    if (multipartFile == null) {

                        Map<String, Object> params = new HashMap<String, Object>();

                        params.put("state", "ERROR");

                        return params;

                    } else {

                        return images(multipartFile, request, action);

                    }

                }

            case "uploadfile": // 上传文件

                return "文件处理方法";

            default:

                return "无效action";

        }



    }
        public Map<String, Object> images(MultipartFile upfile, HttpServletRequest request, String action) {

        Map<String, Object> params = new HashMap<String, Object>();

        try {

            String basePath = null;

            String visitUrl = null;

            if (basePath == null || "".equals(basePath)) {

                basePath = picVideoStorageUrl//与properties文件中lyz.uploading.url相同,未读取到文件数据时为basePath赋默认值

            }

            String fileMD5 = Md5Util.getFileMD5String(upfile);

            if (visitUrl == null || "".equals(visitUrl)) {

                visitUrl = "/ued/getUploadImg/"; //与properties文件中lyz.visit.url相同,未读取到文件数据时为visitUrl赋默认值

            }

            String ext = StringUtils.getExt(upfile.getOriginalFilename());

            String fileName = fileMD5 + "." + ext;

            StringBuilder sb = new StringBuilder();

            //拼接保存路径

            sb.append(basePath).append(fileName);

            visitUrl = visitUrl.concat(fileName);

            File f = new File(sb.toString());

            if (!f.exists()) { //文件不存在 则保存下来

                f.getParentFile().mkdirs();

                OutputStream out = new FileOutputStream(f);

                FileCopyUtils.copy(upfile.getInputStream(), out);

            }

            params.put("state", "SUCCESS");

            params.put("url", visitUrl);

            params.put("size", upfile.getSize());

            params.put("original", fileName);

            params.put("type", upfile.getContentType());

        } catch (Exception e) {

            params.put("state", "ERROR");

        }

        return params;

    }



    private String getConfig() throws Exception {

        File file = ResourceUtils.getFile("classpath:ueditor_config.json");

        String json = FileUtils.readFileToString(file, "utf-8");

        return json;

    }



    @RequestMapping(value = "/getUploadImg/{photoName:.+}")

    @ResponseBody

    public void getUploadImg(@PathVariable String photoName, HttpServletRequest request, HttpServletResponse response) {

        FileInputStream in;

        response.setContentType("application/octet-stream;charset=UTF-8");

        try {

            //图片读取路径

            String picUrl = picVideoStorageUrl;

            in = new FileInputStream(picUrl + photoName);

            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();

        }

    }

 

6:将编辑器源码ueditor/jsp/config.json文件复制到 resources目录下 ,并重命名为 ueditor_config.json

 

7:修改编辑器源码中ueditor/ueditor.config.js文件里面的serverUrl值为/ued/config,这样在上传图片、上传视频、获取配置文件的时候就会调用这个方法,再在后面加上action=这个属性,到这里为止,百度编辑器的基本功能就可以用了,但是会有很多坑,下面我们来处理出现的坑。

 

8:视频src值丢失

在上传视频后,如果对视频进行对齐操作、查看源码、按撤销操作等之后视频vedio标签中的src值会为空,这个问题是白名单的问题,修改ueditor.config.js文件中的whitList改为whiteList就可以解决了。。

 

9: 编辑器视频在IE11上的预览问题

 

修改dialogs/video/video.js文件,将

function addUrlChangeListener(url) {

    if (browser.ie) {

        url.onpropertychange = function () {

            createPreviewVideo(this.value);

        }

    else

        {

            url.addEventListener("input", function () {

                createPreviewVideo(this.value);

            }, false);

        }

    }

}

 

改为:

 

/**

 * 监听url改变事件 ie9以上使用oninput属性监听,onpropertychange不稳定 ghc

 * @param url

 */

function addUrlChangeListener(url){

    if (browser.ie) {

        if(browser.ie11Compat==true

            || browser.ie9Compat == true){

            url.oninput = function () {

                createPreviewVideo( this.value );

            }

        }else{

            //ie9以下

            url.onpropertychange = function () {

                createPreviewVideo( this.value );

            }

        }

    } else {

        url.addEventListener( "input", function () {

            createPreviewVideo( this.value );

        }, false );

    }

}

这样处理了之后还是不能预览,还要修改ueditor.all.js中的17769行代码

html.push(creatInsertStr( vi.url, vi.width || 420vi.height || 280, id + i, null, cl, 'image'));

改为

html.push(creatInsertStr( vi.url, vi.width || 420vi.height || 280, id + i, null, cl, 'video'));

 

10:视频第一帧没有显示出来,导致太丑了

在ueditor.all.js,里面找到creatInsertStr 函数:

case 'video':

    var ext = url.substr(url.lastIndexOf('.') + 1);

    if(ext == 'ogv') ext = 'ogg';

    str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"': '') +

        ' controls  preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +

        '<source src="' + url + '" type="video/' + ext + '" /></video>';

    break;
修改修改:controls="controls" preload="true" 就可以将第一帧加载出来了,这样美多啦
 

11: 编辑器的内容适配手机端

百度编辑器会对img vedio标签的width height样式给了固定的值,要想办法修改这两个样式,解决的代码如下:

<style>

   #register img{

      width: 100% !important;

      height: auto !important;

   }

   #register video{

      width: 100% !important;

      height: auto !important;

   }

</style>

<div id="register" class="full_height">

   ${ue_data}

</div>

 

12:编辑的过程中实现预览功能,可以在手机端预览也可以在pc端预览

<script type="text/javascript">

    function preview(type) {



        $.ajax({

            type: 'POST',

            url: '/user/preview',

            data: {'data':ue.getContent()},

            success: function (data) {

                console.log(ue.getContent())

                var feture = '' ;

                if (type == 0){

                    feture = 'width=375,height=667';

                }

                var w = window.open('', '_blank', feture),

                    d = w.document;

                d.open();

                d.write(data);

                d.close();

            },

            dataType: 'html'

        });

        //



    }



</script>

这个思路是通过ajax向后台传输编辑器的内容到后台,后台组装页面返回这个页面的html内容,然后通过window.open来_bank打开一个新的窗口,往窗口写入html内容,就可以显示啦。

 

其中两个预览按钮如下:

<input type="button" value="手机端预览" onclick="preview(0)"/>

<input type="button" value="PC预览" onclick="preview(1)"/>

 

版权声明:本文为wahaha13168原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/wahaha13168/article/details/81251709