首页 > 技术文章 > umeditor 上传图片 相对路径的设置和保存

linvan 2018-06-03 18:02 原文

此篇文章仅献给已实现百度富文本编辑器,想要设置相对路径并保存到数据库,方便以后项目迁移。

使用的版本为1.2.3,适用图片上传中点击以及拖拽功能。

        //保存图片相对地址的设置
        //1.请修改Uploader.java的getPhysicalPath()方法,设置返回的地址
        //2.请修改imageUp.jsp中的相对地址result
        //3.请修改image.js中的getAllPic()设置src、_src返回值

 1、修改后台代码Uploader.java

    /**
     * 根据传入的虚拟路径获取物理路径
     * 
     * @param path
     * @return
     */
    private String getPhysicalPath(String path) {
        //原版:上传文件放在请求路径(百度编辑器)上一级
//        String servletPath = this.request.getServletPath();
//        String realPath = this.request.getSession().ge tServletContext()
//                .getRealPath(servletPath);
//        return new File(realPath).getParent() +"/" +path;
        
        //修改版:上传文件放在webapp下
        String servletContext = this.request.getSession().getServletContext().getRealPath("");
        return new File(servletContext).getParent() +"/" +path;
    }

2、修改imageUp.jsp

    //String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize() +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
    String pathPre = "../../../../../"; //修改版:根据imageUp.jsp相对位置进行修改,此处图片放在webapp下(不同位置自行修改)
    String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize() +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ pathPre + up.getUrl() +"\"}";

3、修改image.js

getAllPic: function (sel, $w, editor) {
            var me = this,
                arr = [],
                $imgs = $(sel, $w);

            $.each($imgs, function (index, node) {
                $(node).removeAttr("width").removeAttr("height");

//                if (node.width > editor.options.initialFrameWidth) {
//                    me.scale(node, editor.options.initialFrameWidth -
//                        parseInt($(editor.body).css("padding-left"))  -
//                        parseInt($(editor.body).css("padding-right")));
//                }
                //修改版:设置为相对路径(请按需修改)
                var srcFixed = node.src;
                srcFixed = srcFixed.slice(srcFixed.indexOf('upload'));
                srcFixed = "../../../../../" + srcFixed;
                return arr.push({
                    //_src: node.src,
                    //src: node.sr
                    _src: srcFixed,
                    src: srcFixed
                });
            });

            return arr;
        },

这样,在数据库中保存的数据就是相对地址了,与IP、域名无关。

 

推荐阅读