百度UEditor自定义上传文件存储路径

这是基于SSM项目中,使用freemaker加UEditor富文本编辑器修改的,不过使用与JSP的UEditor大同小异,修改后的功能是可以配置上传图片、文件、涂鸦等的存储路径,而不是默认地存储在项目路径下。

首先,增加ueditor.properties配置文件,内容为:

#上传文件存储路径
ueditor.imagePath=F:/jblog/

修改UEditorController,如果是使用JSP页面的,对应修改controller.jsp:
原本的UEditorController为:

@Controller
@RequestMapping("/static/ueditor")
public class UEditorController {


    @RequestMapping("/jsp/controller")
    public void writePage(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
        request.setCharacterEncoding( "utf-8" );
        response.setHeader("Content-Type" , "text/html");

        String rootPath = request.getSession().getServletContext().getRealPath("/");
        response.getWriter().write(new ActionEnter(request, rootPath).exec());
    }
}

修改后:

@Controller
@RequestMapping("/static/ueditor")
public class UEditorController {

    private static String saveRootPath;

    static {
        try {
            Properties prop = new Properties();
            InputStream inStream = (new DefaultResourceLoader()).getResource("classpath:ueditor.properties").getInputStream();
            prop.load(inStream);
            saveRootPath = prop.getProperty("ueditor.imagePath");
        } catch (Exception e) {
            throw new RuntimeException("从ueditor.properties配置文件中获取ueditor图片存储位置失败", e);
        }
    }

    @RequestMapping("/jsp/controller")
    public void writePage(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
        request.setCharacterEncoding( "utf-8" );
        response.setHeader("Content-Type" , "text/html");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        response.getWriter().write(new ActionEnter(request, rootPath, saveRootPath).exec());
    }
}

此时,会发现new ActionEnter(request, rootPath, saveRootPath)报错,是因为ActionEnter构造器只有两个参数的,这里需要修改ueditor.jar中的类。

修改ConfigManager类:

//增加字段saveRootPath
...
private String saveRootPath = null;
...
//构造器增加参数saveRootPath,
//并在构造器中对saveRootPath赋值
private ConfigManager(String rootPath, String contextPath, String saveRootPath, String uri) throws FileNotFoundException, IOException {
        rootPath = rootPath.replace("\\", "/");
        this.saveRootPath = saveRootPath;
        this.rootPath = rootPath;
        this.contextPath = contextPath;
        if (contextPath.length() > 0) {
            this.originalPath = this.rootPath + uri.substring(contextPath.length());
        } else {
            this.originalPath = this.rootPath + uri;
        }

        this.initEnv();
}
//getInstance方法参数saveRootPath,调用修改后的构造器
public static ConfigManager getInstance(String rootPath, String contextPath, String saveRootPath, String uri) {
        try {
            return new ConfigManager(rootPath, contextPath, saveRootPath, uri);
        } catch (Exception var4) {
            return null;
        }
}
...
//把saveRootPath设置到config中
public Map<String, Object> getConfig(int type) {
        Map<String, Object> conf = new HashMap();
        String savePath = null;
        ...
        conf.put("savePath", savePath);
        conf.put("rootPath", this.rootPath);
        conf.put("saveRootPath", this.saveRootPath);
        return conf;
    }

修改ActionEnter类:

    ...
    //增加字段saveRootPath
    private String saveRootPath = null;
    ...
    //修改ActionEnter构造器,调用修改后的ConfigManager.getInstance方法
    public ActionEnter(HttpServletRequest request, String rootPath, String saveRootPath) {
        this.request = request;
        this.rootPath = rootPath;
        this.saveRootPath = saveRootPath;
        this.actionType = request.getParameter("action");
        this.contextPath = request.getContextPath();
        this.configManager = ConfigManager.getInstance(this.rootPath, this.contextPath, this.saveRootPath, request.getRequestURI());
    }

修改BinaryUploader类:

public class BinaryUploader {
    public BinaryUploader() {
    }

    public static final State save(HttpServletRequest request, Map<String, Object> conf) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
            MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
            String savePath = (String)conf.get("savePath");
            String originFileName = multipartFile.getOriginalFilename();
            String suffix = FileType.getSuffixByFilename(originFileName);
            originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
            savePath = savePath + suffix;
            long maxSize = ((Long)conf.get("maxSize")).longValue();
            if (!validType(suffix, (String[])((String[])conf.get("allowFiles")))) {
                return new BaseState(false, 8);
            } else {
                savePath = PathFormat.parse(savePath, originFileName);
                int index = savePath.lastIndexOf('/');
                String saveRootPath = (String)conf.get("saveRootPath");
                String physicalPath = saveRootPath + savePath.substring(0, index);
                File targetFile = new File(physicalPath);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }

                State storageState = StorageManager.saveFileByInputStream(multipartFile.getInputStream(), saveRootPath + savePath, maxSize);
                if (storageState.isSuccess()) {
                    storageState.putInfo("url", PathFormat.format(savePath));
                    storageState.putInfo("type", suffix);
                    storageState.putInfo("original", originFileName + suffix);
                }

                return storageState;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return new BaseState(false, 4);
        }
    }

    private static boolean validType(String type, String[] allowTypes) {
        List<String> list = Arrays.asList(allowTypes);
        return list.contains(type);
    }
}

到这里完成了对图片、视频、文件的存储路径的修改,如果需要用到涂鸦的功能,还需要修改Base64Uploader类:

    public static State save(String content, Map<String, Object> conf) {
        byte[] data = decode(content);
        long maxSize = ((Long)conf.get("maxSize")).longValue();
        if (!validSize(data, maxSize)) {
            return new BaseState(false, 1);
        } else {
            String suffix = FileType.getSuffix("JPG");
            String savePath = PathFormat.parse((String)conf.get("savePath"), (String)conf.get("filename"));
            savePath = savePath + suffix;
            String physicalPath = (String)conf.get("saveRootPath") + savePath;
            State storageState = StorageManager.saveBinaryFile(data, physicalPath);
            if (storageState.isSuccess()) {
                storageState.putInfo("url", PathFormat.format(savePath));
                storageState.putInfo("type", suffix);
                storageState.putInfo("original", "");
            }

            return storageState;
        }
    }

完成了上传文件的存储设置后,图片还不能回显,在spring mvc配置文件中增加配置:

    <context:property-placeholder location="classpath:ueditor.properties" />
    <mvc:resources  mapping="/ueditor/upload/**" location= "file:${ueditor.imagePath}/ueditor/upload/" />

也可以写一个handle处理文件请求,参考:http://blog.csdn.net/yuancenyi/article/details/53327414

配置文件config.json内容为:

/* 上传图片配置项 */
    "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
    "imageFieldName": "upfile", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制,单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "/admin", /* 图片访问路径前缀 */
    "imagePathFormat": "/ueditor/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"
    ......

修改后的效果为:
图1

图2

图3

还有其中截图功能不能使用的问题尚未解决
图4
点击截图后,提示需要安装截图插件,安装完成后点击截图依旧出现该界面,再火狐,谷歌,还有Windows10自带的浏览器都是如此,只有IE可以调用出截图功能,可是会出现错误:
图5

异常信息为:

org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: Stream ended unexpectedly
    at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:168)
    at org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:142)
    at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1104)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:936)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)
    at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
    at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
    at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
    at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
    at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
    at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
    at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
    at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)
    at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2555)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2544)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.commons.fileupload.FileUploadException: Stream ended unexpectedly
    at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:362)
    at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
    at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:158)
    ... 50 more
Caused by: org.apache.commons.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly
    at org.apache.commons.fileupload.MultipartStream.readHeaders(MultipartStream.java:540)
    at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:1038)
    at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.hasNext(FileUploadBase.java:1106)
    at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:339)
    ... 52 more

看起来是流中断了,此问题未能解决。

jar包下载地址:http://download.csdn.net/download/maijia0754/10257242

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值