├── ueditor-demo ├── src │ └── main │ │ ├── resources │ │ ├── application.yml │ │ └── config.json │ │ ├── webapp │ │ ├── index.jsp │ │ └── WEB-INF │ │ │ └── web.xml │ │ └── java │ │ └── cn │ │ └── com │ │ └── lee │ │ ├── common │ │ ├── ueditor │ │ │ ├── define │ │ │ │ ├── ActionState.java │ │ │ │ ├── State.java │ │ │ │ ├── MIMEType.java │ │ │ │ ├── FileType.java │ │ │ │ ├── ActionMap.java │ │ │ │ ├── BaseState.java │ │ │ │ ├── MultiState.java │ │ │ │ └── AppInfo.java │ │ │ ├── Encoder.java │ │ │ ├── upload │ │ │ │ ├── Uploader.java │ │ │ │ ├── Base64Uploader.java │ │ │ │ ├── BinaryUploader.java │ │ │ │ └── StorageManager.java │ │ │ ├── SpringUtil.java │ │ │ ├── hunter │ │ │ │ ├── FileManager.java │ │ │ │ └── ImageHunter.java │ │ │ ├── ActionEnter.java │ │ │ ├── PathFormat.java │ │ │ └── ConfigManager.java │ │ └── config │ │ │ └── CrosConfig.java │ │ ├── UeditorApplication.java │ │ └── controller │ │ └── UeditorController.java ├── pom.xml └── .factorypath ├── .gitignore └── README.md /ueditor-demo/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8081 3 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Hello World!

4 | 5 | 6 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/define/ActionState.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.define; 2 | 3 | public enum ActionState { 4 | UNKNOW_ERROR 5 | } 6 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | Archetype Created Web Application 7 | 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # maven ignore 2 | target/ 3 | 4 | # eclipse ignore 5 | .settings/ 6 | .project 7 | .classpath 8 | 9 | # idea ignore 10 | .idea/ 11 | *.ipr 12 | *.iml 13 | *.iws 14 | 15 | # temp ignore 16 | *.log 17 | *.cache 18 | *.diff 19 | *.patch 20 | *.tmp 21 | 22 | # system ignore 23 | .DS_Store 24 | Thumbs.db 25 | 26 | # project ignore 27 | **/tmp 28 | pom.xml.versionsBackup 29 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/define/State.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.define; 2 | 3 | /** 4 | * 处理状态接口 5 | * @author hancong03@baidu.com 6 | * 7 | */ 8 | public interface State { 9 | 10 | public boolean isSuccess (); 11 | 12 | public void putInfo( String name, String val ); 13 | 14 | public void putInfo ( String name, long val ); 15 | 16 | public String toJSONString (); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/Encoder.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor; 2 | 3 | public class Encoder { 4 | 5 | public static String toUnicode ( String input ) { 6 | 7 | StringBuilder builder = new StringBuilder(); 8 | char[] chars = input.toCharArray(); 9 | 10 | for ( char ch : chars ) { 11 | 12 | if ( ch < 256 ) { 13 | builder.append( ch ); 14 | } else { 15 | builder.append( "\\u" + Integer.toHexString( ch& 0xffff ) ); 16 | } 17 | 18 | } 19 | 20 | return builder.toString(); 21 | 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/define/MIMEType.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.define; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MIMEType { 7 | 8 | public static final Map types = new HashMap(){{ 9 | put( "image/gif", ".gif" ); 10 | put( "image/jpeg", ".jpg" ); 11 | put( "image/jpg", ".jpg" ); 12 | put( "image/png", ".png" ); 13 | put( "image/bmp", ".bmp" ); 14 | }}; 15 | 16 | public static String getSuffix ( String mime ) { 17 | return MIMEType.types.get( mime ); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/define/FileType.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.define; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class FileType { 7 | 8 | public static final String JPG = "JPG"; 9 | 10 | private static final Map types = new HashMap(){{ 11 | 12 | put( FileType.JPG, ".jpg" ); 13 | 14 | }}; 15 | 16 | public static String getSuffix ( String key ) { 17 | return FileType.types.get( key ); 18 | } 19 | 20 | /** 21 | * 根据给定的文件名,获取其后缀信息 22 | * @param filename 23 | * @return 24 | */ 25 | public static String getSuffixByFilename ( String filename ) { 26 | 27 | return filename.substring( filename.lastIndexOf( "." ) ).toLowerCase(); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/UeditorApplication.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * 11 | * @author Guoqing 12 | * @date 2017-11-29 13 | * 14 | */ 15 | @RestController 16 | @SpringBootApplication 17 | public class UeditorApplication { 18 | 19 | private static final Logger LOGGER = LoggerFactory.getLogger(UeditorApplication.class); 20 | 21 | public static void main(String[] args) { 22 | SpringApplication application = new SpringApplication(UeditorApplication.class); 23 | application.run(args); 24 | LOGGER.info("Ueditor application started!!!"); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/upload/Uploader.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.upload; 2 | 3 | 4 | import java.util.Map; 5 | import javax.servlet.http.HttpServletRequest; 6 | import cn.com.lee.common.ueditor.define.State; 7 | 8 | 9 | public class Uploader { 10 | private HttpServletRequest request = null; 11 | private Map conf = null; 12 | 13 | public Uploader(HttpServletRequest request, Map conf) { 14 | this.request = request; 15 | this.conf = conf; 16 | } 17 | 18 | public final State doExec() { 19 | String filedName = (String) this.conf.get("fieldName"); 20 | State state = null; 21 | 22 | if ("true".equals(this.conf.get("isBase64"))) { 23 | state = Base64Uploader.save(this.request.getParameter(filedName), 24 | this.conf); 25 | } else { 26 | state = BinaryUploader.save(this.request, this.conf); 27 | } 28 | 29 | return state; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/SpringUtil.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class SpringUtil implements ApplicationContextAware { 10 | 11 | private static ApplicationContext applicationContext; 12 | 13 | @Override 14 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 15 | if(SpringUtil.applicationContext == null){ 16 | SpringUtil.applicationContext = applicationContext; 17 | } 18 | System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringUtil.applicationContext+"========"); 19 | } 20 | 21 | public static ApplicationContext getApplicationContext() { 22 | return applicationContext; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/controller/UeditorController.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.controller; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | import org.springframework.web.bind.annotation.CrossOrigin; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.ResponseBody; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import cn.com.lee.common.ueditor.ActionEnter; 13 | 14 | /** 15 | * 用于处理关于ueditor插件相关的请求 16 | * @author Guoqing 17 | * @date 2017-11-29 18 | * 19 | */ 20 | @RestController 21 | @CrossOrigin 22 | @RequestMapping("/ueditor") 23 | public class UeditorController { 24 | 25 | @RequestMapping(value = "/exec") 26 | @ResponseBody 27 | public String exec(HttpServletRequest request) throws UnsupportedEncodingException{ 28 | request.setCharacterEncoding("utf-8"); 29 | String rootPath = request.getRealPath("/"); 30 | return new ActionEnter( request, rootPath ).exec(); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/config/CrosConfig.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.cors.CorsConfiguration; 6 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 7 | import org.springframework.web.filter.CorsFilter; 8 | 9 | /** 10 | * 跨域请求处理 11 | * @author Guoqing 12 | * 13 | */ 14 | @Configuration 15 | public class CrosConfig { 16 | 17 | private CorsConfiguration buildConfig() { 18 | CorsConfiguration corsConfiguration = new CorsConfiguration(); 19 | corsConfiguration.addAllowedOrigin("*"); // 1 20 | corsConfiguration.addAllowedHeader("*"); // 2 21 | corsConfiguration.addAllowedMethod("*"); // 3 22 | return corsConfiguration; 23 | } 24 | 25 | @Bean 26 | public CorsFilter corsFilter() { 27 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 28 | source.registerCorsConfiguration("/**", buildConfig()); // 4 29 | return new CorsFilter(source); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/define/ActionMap.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.define; 2 | 3 | import java.util.Map; 4 | import java.util.HashMap; 5 | 6 | /** 7 | * 定义请求action类型 8 | * @author hancong03@baidu.com 9 | * 10 | */ 11 | @SuppressWarnings("serial") 12 | public final class ActionMap { 13 | 14 | public static final Map mapping; 15 | // 获取配置请求 16 | public static final int CONFIG = 0; 17 | public static final int UPLOAD_IMAGE = 1; 18 | public static final int UPLOAD_SCRAWL = 2; 19 | public static final int UPLOAD_VIDEO = 3; 20 | public static final int UPLOAD_FILE = 4; 21 | public static final int CATCH_IMAGE = 5; 22 | public static final int LIST_FILE = 6; 23 | public static final int LIST_IMAGE = 7; 24 | 25 | static { 26 | mapping = new HashMap(){{ 27 | put( "config", ActionMap.CONFIG ); 28 | put( "uploadimage", ActionMap.UPLOAD_IMAGE ); 29 | put( "uploadscrawl", ActionMap.UPLOAD_SCRAWL ); 30 | put( "uploadvideo", ActionMap.UPLOAD_VIDEO ); 31 | put( "uploadfile", ActionMap.UPLOAD_FILE ); 32 | put( "catchimage", ActionMap.CATCH_IMAGE ); 33 | put( "listfile", ActionMap.LIST_FILE ); 34 | put( "listimage", ActionMap.LIST_IMAGE ); 35 | }}; 36 | } 37 | 38 | public static int getType ( String key ) { 39 | return ActionMap.mapping.get( key ); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UeditorSpringboot 2 | this is ueditor controller demo project. 3 | 4 | ### 说明 5 | 后端部分的重点在于处理文件上传,文件上传部分需要自己动手改写代码,对接自己的文件服务或者存储,总之该DEMO中的代码没有对最终存储这一步做处理; 6 | 你需要修改的代码的位置为 `cn.com.lee.common.ueditor.upload.StorageManager` 类下的TODO: 7 | ```java 8 | public static State saveFileByInputStream(HttpServletRequest request, InputStream is, String path, String picName, 9 | long maxSize) { 10 | 11 | State state = null; 12 | File tmpFile = getTmpFile(); 13 | byte[] dataBuf = new byte[ 2048 ]; 14 | 15 | try { 16 | //转成字节流 17 | ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 18 | int rc = 0; 19 | while ((rc = is.read(dataBuf, 0, 100)) > 0) { 20 | swapStream.write(dataBuf, 0, rc); 21 | } 22 | 23 | dataBuf = swapStream.toByteArray(); 24 | swapStream.flush(); 25 | swapStream.close(); 26 | 27 | if (tmpFile.length() > maxSize) { 28 | tmpFile.delete(); 29 | return new BaseState(false, AppInfo.MAX_SIZE); 30 | } 31 | //:TODO 32 | /** 33 | * 此处调用文件上传服务,并获取返回结果返回 34 | */ 35 | //UploadResult result = baseFileService.upload(dataBuf, picName, "OM", null); 36 | 37 | boolean success = true; 38 | //如果上传成功 39 | if (success) { 40 | state = new BaseState(true); 41 | state.putInfo( "size", tmpFile.length() ); 42 | state.putInfo( "title", "");//文件名填入此处 43 | state.putInfo( "url", "");//文件访问的url填入此处 44 | tmpFile.delete(); 45 | }else{ 46 | state = new BaseState(false, 4); 47 | tmpFile.delete(); 48 | } 49 | 50 | return state; 51 | 52 | } catch (IOException e) { 53 | } 54 | return new BaseState(false, AppInfo.IO_ERROR); 55 | } 56 | ``` 57 | 最终返回的URL地址必须是HTTP、HTTPS开头的网络地址,如果不是请在返回之前做好处理; 58 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/upload/Base64Uploader.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.upload; 2 | 3 | import java.util.Map; 4 | 5 | import org.apache.commons.codec.binary.Base64; 6 | import org.apache.commons.codec.binary.StringUtils; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import cn.com.lee.common.ueditor.PathFormat; 11 | import cn.com.lee.common.ueditor.define.FileType; 12 | import cn.com.lee.common.ueditor.define.State; 13 | import cn.com.lee.common.ueditor.define.AppInfo; 14 | import cn.com.lee.common.ueditor.define.BaseState; 15 | 16 | public final class Base64Uploader { 17 | static Logger logger = LoggerFactory.getLogger(Base64Uploader.class); 18 | public static State save(String content, Map conf) { 19 | 20 | byte[] data = decode(content); 21 | 22 | long maxSize = ((Long) conf.get("maxSize")).longValue(); 23 | 24 | if (!validSize(data, maxSize)) { 25 | return new BaseState(false, AppInfo.MAX_SIZE); 26 | } 27 | 28 | String suffix = FileType.getSuffix("JPG"); 29 | 30 | String savePath = PathFormat.parse((String) conf.get("savePath"), 31 | (String) conf.get("filename")); 32 | String localSavePathPrefix = PathFormat.parse((String) conf.get("localSavePathPrefix"), 33 | (String) conf.get("filename")); 34 | savePath = savePath + suffix; 35 | localSavePathPrefix = localSavePathPrefix + suffix; 36 | String physicalPath = localSavePathPrefix; 37 | logger.info("Base64Uploader physicalPath:{},savePath:{}",localSavePathPrefix,savePath); 38 | State storageState = StorageManager.saveBinaryFile(data, physicalPath); 39 | 40 | if (storageState.isSuccess()) { 41 | storageState.putInfo("url", PathFormat.format(savePath)); 42 | storageState.putInfo("type", suffix); 43 | storageState.putInfo("original", ""); 44 | } 45 | 46 | return storageState; 47 | } 48 | 49 | private static byte[] decode(String content) { 50 | return Base64.decodeBase64(StringUtils.getBytesUtf8(content)); 51 | } 52 | 53 | private static boolean validSize(byte[] data, long length) { 54 | return data.length <= length; 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/define/BaseState.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.define; 2 | 3 | import java.util.HashMap; 4 | import java.util.Iterator; 5 | import java.util.Map; 6 | 7 | import cn.com.lee.common.ueditor.Encoder; 8 | 9 | 10 | 11 | public class BaseState implements State { 12 | 13 | private boolean state = false; 14 | private String info = null; 15 | 16 | private Map infoMap = new HashMap(); 17 | 18 | public BaseState () { 19 | this.state = true; 20 | } 21 | 22 | public BaseState ( boolean state ) { 23 | this.setState( state ); 24 | } 25 | 26 | public BaseState ( boolean state, String info ) { 27 | this.setState( state ); 28 | this.info = info; 29 | } 30 | 31 | public BaseState ( boolean state, int infoCode ) { 32 | this.setState( state ); 33 | this.info = AppInfo.getStateInfo( infoCode ); 34 | } 35 | 36 | public boolean isSuccess () { 37 | return this.state; 38 | } 39 | 40 | public void setState ( boolean state ) { 41 | this.state = state; 42 | } 43 | 44 | public void setInfo ( String info ) { 45 | this.info = info; 46 | } 47 | 48 | public void setInfo ( int infoCode ) { 49 | this.info = AppInfo.getStateInfo( infoCode ); 50 | } 51 | 52 | @Override 53 | public String toJSONString() { 54 | return this.toString(); 55 | } 56 | 57 | public String toString () { 58 | 59 | String key = null; 60 | String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info; 61 | 62 | StringBuilder builder = new StringBuilder(); 63 | 64 | builder.append( "{\"state\": \"" + stateVal + "\"" ); 65 | 66 | Iterator iterator = this.infoMap.keySet().iterator(); 67 | 68 | while ( iterator.hasNext() ) { 69 | 70 | key = iterator.next(); 71 | 72 | builder.append( ",\"" + key + "\": \"" + this.infoMap.get(key) + "\"" ); 73 | 74 | } 75 | 76 | builder.append( "}" ); 77 | 78 | return Encoder.toUnicode( builder.toString() ); 79 | 80 | } 81 | 82 | @Override 83 | public void putInfo(String name, String val) { 84 | this.infoMap.put(name, val); 85 | } 86 | 87 | @Override 88 | public void putInfo(String name, long val) { 89 | this.putInfo(name, val+""); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /ueditor-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | cn.com.lee 5 | ueditor-demo 6 | jar 7 | 0.0.1-SNAPSHOT 8 | ueditor-demo Maven Webapp 9 | http://maven.apache.org 10 | 11 | 12 | UTF-8 13 | 14 | 1.8 15 | 16 | 17 | 18 | org.springframework.boot 19 | spring-boot-starter-parent 20 | 1.5.2.RELEASE 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | junit 29 | junit 30 | test 31 | 32 | 33 | 34 | org.json 35 | json 36 | 20160517 37 | 38 | 39 | commons-codec 40 | commons-codec 41 | 1.10 42 | 43 | 44 | commons-fileupload 45 | commons-fileupload 46 | 1.3.1 47 | 48 | 49 | 50 | commons-io 51 | commons-io 52 | 2.6 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-configuration-processor 57 | true 58 | 59 | 60 | 61 | ueditor-demo 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-maven-plugin 66 | 67 | 68 | 69 | 70 | 71 | spring-milestone 72 | http://repo.spring.io/libs-release 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/define/MultiState.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.define; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import cn.com.lee.common.ueditor.Encoder; 10 | 11 | 12 | 13 | 14 | /** 15 | * 多状态集合状态 16 | * 其包含了多个状态的集合, 其本身自己也是一个状态 17 | * @author hancong03@baidu.com 18 | * 19 | */ 20 | public class MultiState implements State { 21 | 22 | private boolean state = false; 23 | private String info = null; 24 | private Map intMap = new HashMap(); 25 | private Map infoMap = new HashMap(); 26 | private List stateList = new ArrayList(); 27 | 28 | public MultiState ( boolean state ) { 29 | this.state = state; 30 | } 31 | 32 | public MultiState ( boolean state, String info ) { 33 | this.state = state; 34 | this.info = info; 35 | } 36 | 37 | public MultiState ( boolean state, int infoKey ) { 38 | this.state = state; 39 | this.info = AppInfo.getStateInfo( infoKey ); 40 | } 41 | 42 | @Override 43 | public boolean isSuccess() { 44 | return this.state; 45 | } 46 | 47 | public void addState ( State state ) { 48 | stateList.add( state.toJSONString() ); 49 | } 50 | 51 | /** 52 | * 该方法调用无效果 53 | */ 54 | @Override 55 | public void putInfo(String name, String val) { 56 | this.infoMap.put(name, val); 57 | } 58 | 59 | @Override 60 | public String toJSONString() { 61 | 62 | String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info; 63 | 64 | StringBuilder builder = new StringBuilder(); 65 | 66 | builder.append( "{\"state\": \"" + stateVal + "\"" ); 67 | 68 | // 数字转换 69 | Iterator iterator = this.intMap.keySet().iterator(); 70 | 71 | while ( iterator.hasNext() ) { 72 | 73 | stateVal = iterator.next(); 74 | 75 | builder.append( ",\""+ stateVal +"\": " + this.intMap.get( stateVal ) ); 76 | 77 | } 78 | 79 | iterator = this.infoMap.keySet().iterator(); 80 | 81 | while ( iterator.hasNext() ) { 82 | 83 | stateVal = iterator.next(); 84 | 85 | builder.append( ",\""+ stateVal +"\": \"" + this.infoMap.get( stateVal ) + "\"" ); 86 | 87 | } 88 | 89 | builder.append( ", list: [" ); 90 | 91 | 92 | iterator = this.stateList.iterator(); 93 | 94 | while ( iterator.hasNext() ) { 95 | 96 | builder.append( iterator.next() + "," ); 97 | 98 | } 99 | 100 | if ( this.stateList.size() > 0 ) { 101 | builder.deleteCharAt( builder.length() - 1 ); 102 | } 103 | 104 | builder.append( " ]}" ); 105 | 106 | return Encoder.toUnicode( builder.toString() ); 107 | 108 | } 109 | 110 | @Override 111 | public void putInfo(String name, long val) { 112 | this.intMap.put( name, val ); 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/define/AppInfo.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.define; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public final class AppInfo { 7 | 8 | public static final int SUCCESS = 0; 9 | public static final int MAX_SIZE = 1; 10 | public static final int PERMISSION_DENIED = 2; 11 | public static final int FAILED_CREATE_FILE = 3; 12 | public static final int IO_ERROR = 4; 13 | public static final int NOT_MULTIPART_CONTENT = 5; 14 | public static final int PARSE_REQUEST_ERROR = 6; 15 | public static final int NOTFOUND_UPLOAD_DATA = 7; 16 | public static final int NOT_ALLOW_FILE_TYPE = 8; 17 | 18 | public static final int INVALID_ACTION = 101; 19 | public static final int CONFIG_ERROR = 102; 20 | 21 | public static final int PREVENT_HOST = 201; 22 | public static final int CONNECTION_ERROR = 202; 23 | public static final int REMOTE_FAIL = 203; 24 | 25 | public static final int NOT_DIRECTORY = 301; 26 | public static final int NOT_EXIST = 302; 27 | 28 | public static final int ILLEGAL = 401; 29 | 30 | public static Map info = new HashMap(){{ 31 | 32 | put( AppInfo.SUCCESS, "SUCCESS" ); 33 | 34 | // 无效的Action 35 | put( AppInfo.INVALID_ACTION, "\u65E0\u6548\u7684Action" ); 36 | // 配置文件初始化失败 37 | put( AppInfo.CONFIG_ERROR, "\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u5931\u8D25" ); 38 | // 抓取远程图片失败 39 | put( AppInfo.REMOTE_FAIL, "\u6293\u53D6\u8FDC\u7A0B\u56FE\u7247\u5931\u8D25" ); 40 | 41 | // 被阻止的远程主机 42 | put( AppInfo.PREVENT_HOST, "\u88AB\u963B\u6B62\u7684\u8FDC\u7A0B\u4E3B\u673A" ); 43 | // 远程连接出错 44 | put( AppInfo.CONNECTION_ERROR, "\u8FDC\u7A0B\u8FDE\u63A5\u51FA\u9519" ); 45 | 46 | // "文件大小超出限制" 47 | put( AppInfo.MAX_SIZE, "\u6587\u4ef6\u5927\u5c0f\u8d85\u51fa\u9650\u5236" ); 48 | // 权限不足, 多指写权限 49 | put( AppInfo.PERMISSION_DENIED, "\u6743\u9650\u4E0D\u8DB3" ); 50 | // 创建文件失败 51 | put( AppInfo.FAILED_CREATE_FILE, "\u521B\u5EFA\u6587\u4EF6\u5931\u8D25" ); 52 | // IO错误 53 | put( AppInfo.IO_ERROR, "IO\u9519\u8BEF" ); 54 | // 上传表单不是multipart/form-data类型 55 | put( AppInfo.NOT_MULTIPART_CONTENT, "\u4E0A\u4F20\u8868\u5355\u4E0D\u662Fmultipart/form-data\u7C7B\u578B" ); 56 | // 解析上传表单错误 57 | put( AppInfo.PARSE_REQUEST_ERROR, "\u89E3\u6790\u4E0A\u4F20\u8868\u5355\u9519\u8BEF" ); 58 | // 未找到上传数据 59 | put( AppInfo.NOTFOUND_UPLOAD_DATA, "\u672A\u627E\u5230\u4E0A\u4F20\u6570\u636E" ); 60 | // 不允许的文件类型 61 | put( AppInfo.NOT_ALLOW_FILE_TYPE, "\u4E0D\u5141\u8BB8\u7684\u6587\u4EF6\u7C7B\u578B" ); 62 | 63 | // 指定路径不是目录 64 | put( AppInfo.NOT_DIRECTORY, "\u6307\u5B9A\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55" ); 65 | // 指定路径并不存在 66 | put( AppInfo.NOT_EXIST, "\u6307\u5B9A\u8DEF\u5F84\u5E76\u4E0D\u5B58\u5728" ); 67 | 68 | // callback参数名不合法 69 | put( AppInfo.ILLEGAL, "Callback\u53C2\u6570\u540D\u4E0D\u5408\u6CD5" ); 70 | 71 | }}; 72 | 73 | public static String getStateInfo ( int key ) { 74 | return AppInfo.info.get( key ); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/hunter/FileManager.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.hunter; 2 | 3 | import java.io.File; 4 | import java.util.Arrays; 5 | import java.util.Collection; 6 | import java.util.Map; 7 | 8 | import org.apache.commons.io.FileUtils; 9 | 10 | import cn.com.lee.common.ueditor.PathFormat; 11 | import cn.com.lee.common.ueditor.define.AppInfo; 12 | import cn.com.lee.common.ueditor.define.BaseState; 13 | import cn.com.lee.common.ueditor.define.MultiState; 14 | import cn.com.lee.common.ueditor.define.State; 15 | 16 | 17 | 18 | public class FileManager { 19 | 20 | private String dir = null; 21 | private String rootPath = null; 22 | private String[] allowFiles = null; 23 | private int count = 0; 24 | 25 | public FileManager ( Map conf ) { 26 | 27 | this.rootPath = (String)conf.get( "rootPath" ); 28 | this.dir = this.rootPath + (String)conf.get( "dir" ); 29 | this.allowFiles = this.getAllowFiles( conf.get("allowFiles") ); 30 | this.count = (Integer)conf.get( "count" ); 31 | 32 | } 33 | 34 | public State listFile ( int index ) { 35 | 36 | File dir = new File( this.dir ); 37 | State state = null; 38 | 39 | if ( !dir.exists() ) { 40 | return new BaseState( false, AppInfo.NOT_EXIST ); 41 | } 42 | 43 | if ( !dir.isDirectory() ) { 44 | return new BaseState( false, AppInfo.NOT_DIRECTORY ); 45 | } 46 | 47 | Collection list = FileUtils.listFiles( dir, this.allowFiles, true ); 48 | 49 | if ( index < 0 || index > list.size() ) { 50 | state = new MultiState( true ); 51 | } else { 52 | Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count ); 53 | state = this.getState( fileList ); 54 | } 55 | 56 | state.putInfo( "start", index ); 57 | state.putInfo( "total", list.size() ); 58 | 59 | return state; 60 | 61 | } 62 | 63 | private State getState ( Object[] files ) { 64 | 65 | MultiState state = new MultiState( true ); 66 | BaseState fileState = null; 67 | 68 | File file = null; 69 | 70 | for ( Object obj : files ) { 71 | if ( obj == null ) { 72 | break; 73 | } 74 | file = (File)obj; 75 | fileState = new BaseState( true ); 76 | fileState.putInfo( "url", PathFormat.format( this.getPath( file ) ) ); 77 | state.addState( fileState ); 78 | } 79 | 80 | return state; 81 | 82 | } 83 | 84 | private String getPath ( File file ) { 85 | 86 | String path = file.getAbsolutePath(); 87 | 88 | return path.replace( this.rootPath, "/" ); 89 | 90 | } 91 | 92 | private String[] getAllowFiles ( Object fileExt ) { 93 | 94 | String[] exts = null; 95 | String ext = null; 96 | 97 | if ( fileExt == null ) { 98 | return new String[ 0 ]; 99 | } 100 | 101 | exts = (String[])fileExt; 102 | 103 | for ( int i = 0, len = exts.length; i < len; i++ ) { 104 | 105 | ext = exts[ i ]; 106 | exts[ i ] = ext.replace( ".", "" ); 107 | 108 | } 109 | 110 | return exts; 111 | 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/upload/BinaryUploader.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.upload; 2 | 3 | import java.io.InputStream; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | import org.apache.commons.fileupload.disk.DiskFileItemFactory; 11 | import org.apache.commons.fileupload.servlet.ServletFileUpload; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.web.multipart.MultipartFile; 15 | import org.springframework.web.multipart.MultipartHttpServletRequest; 16 | 17 | import cn.com.lee.common.ueditor.PathFormat; 18 | import cn.com.lee.common.ueditor.define.AppInfo; 19 | import cn.com.lee.common.ueditor.define.BaseState; 20 | import cn.com.lee.common.ueditor.define.FileType; 21 | import cn.com.lee.common.ueditor.define.State; 22 | 23 | 24 | 25 | public class BinaryUploader { 26 | static Logger logger = LoggerFactory.getLogger(BinaryUploader.class); 27 | 28 | public static final State save(HttpServletRequest request, Map conf) { 29 | 30 | boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null; 31 | 32 | if (!ServletFileUpload.isMultipartContent(request)) { 33 | return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT); 34 | } 35 | 36 | ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); 37 | 38 | if ( isAjaxUpload ) { 39 | upload.setHeaderEncoding( "UTF-8" ); 40 | } 41 | 42 | try { 43 | MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 44 | MultipartFile file = multipartRequest.getFile("upfile"); 45 | 46 | String savePath = (String) conf.get("savePath"); 47 | String localSavePathPrefix = (String) conf.get("localSavePathPrefix"); 48 | String originFileName = file.getOriginalFilename(); 49 | String suffix = FileType.getSuffixByFilename(originFileName); 50 | 51 | originFileName = originFileName.substring(0, originFileName.length() - suffix.length()); 52 | savePath = savePath + suffix; 53 | 54 | long maxSize = ((Long) conf.get("maxSize")).longValue(); 55 | 56 | if (!validType(suffix, (String[]) conf.get("allowFiles"))) { 57 | return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE); 58 | } 59 | savePath = PathFormat.parse(savePath, originFileName); 60 | localSavePathPrefix = localSavePathPrefix + savePath; 61 | String physicalPath = localSavePathPrefix; 62 | logger.info("BinaryUploader physicalPath:{},savePath:{}",localSavePathPrefix,savePath); 63 | InputStream is = file.getInputStream(); 64 | 65 | //在此处调用ftp的上传图片的方法将图片上传到文件服务器 66 | String path = physicalPath.substring(0, physicalPath.lastIndexOf("/")); 67 | String picName = physicalPath.substring(physicalPath.lastIndexOf("/")+1, physicalPath.length()); 68 | State storageState = StorageManager.saveFileByInputStream(request, is, path, picName, maxSize); 69 | 70 | is.close(); 71 | 72 | if (storageState.isSuccess()) { 73 | storageState.putInfo("type", suffix); 74 | storageState.putInfo("original", originFileName + suffix); 75 | } 76 | 77 | return storageState; 78 | } catch (Exception e) { 79 | return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR); 80 | } 81 | } 82 | 83 | private static boolean validType(String type, String[] allowTypes) { 84 | List list = Arrays.asList(allowTypes); 85 | 86 | return list.contains(type); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/ActionEnter.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor; 2 | 3 | import java.util.Map; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | import org.json.JSONException; 8 | import cn.com.lee.common.ueditor.define.ActionMap; 9 | import cn.com.lee.common.ueditor.define.AppInfo; 10 | import cn.com.lee.common.ueditor.define.BaseState; 11 | import cn.com.lee.common.ueditor.define.State; 12 | import cn.com.lee.common.ueditor.hunter.FileManager; 13 | import cn.com.lee.common.ueditor.hunter.ImageHunter; 14 | import cn.com.lee.common.ueditor.upload.Uploader; 15 | 16 | 17 | public class ActionEnter { 18 | 19 | private HttpServletRequest request = null; 20 | 21 | private String rootPath = null; 22 | private String contextPath = null; 23 | 24 | private String actionType = null; 25 | 26 | private ConfigManager configManager = null; 27 | 28 | public ActionEnter ( HttpServletRequest request, String rootPath) { 29 | 30 | this.request = request; 31 | this.rootPath = rootPath; 32 | this.actionType = request.getParameter( "action" ); 33 | this.contextPath = request.getContextPath(); 34 | this.configManager = ConfigManager.getInstance( this.rootPath, this.contextPath, request.getRequestURI() ); 35 | 36 | } 37 | 38 | public String exec () throws JSONException { 39 | 40 | String callbackName = this.request.getParameter("callback"); 41 | 42 | if ( callbackName != null ) { 43 | 44 | if ( !validCallbackName( callbackName ) ) { 45 | return new BaseState( false, AppInfo.ILLEGAL ).toJSONString(); 46 | } 47 | 48 | return this.invoke(); 49 | 50 | } else { 51 | return this.invoke(); 52 | } 53 | 54 | } 55 | 56 | public String invoke() throws JSONException { 57 | 58 | if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) { 59 | return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString(); 60 | } 61 | 62 | if ( this.configManager == null || !this.configManager.valid() ) { 63 | return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString(); 64 | } 65 | 66 | State state = null; 67 | 68 | int actionCode = ActionMap.getType( this.actionType ); 69 | 70 | Map conf = null; 71 | 72 | switch ( actionCode ) { 73 | 74 | case ActionMap.CONFIG: 75 | return this.configManager.getAllConfig().toString(); 76 | 77 | case ActionMap.UPLOAD_IMAGE: 78 | case ActionMap.UPLOAD_SCRAWL: 79 | case ActionMap.UPLOAD_VIDEO: 80 | case ActionMap.UPLOAD_FILE: 81 | conf = this.configManager.getConfig( actionCode ); 82 | state = new Uploader( request, conf ).doExec(); 83 | break; 84 | 85 | case ActionMap.CATCH_IMAGE: 86 | conf = configManager.getConfig( actionCode ); 87 | String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) ); 88 | state = new ImageHunter( conf ).capture( list ); 89 | break; 90 | 91 | case ActionMap.LIST_IMAGE: 92 | case ActionMap.LIST_FILE: 93 | conf = configManager.getConfig( actionCode ); 94 | int start = this.getStartIndex(); 95 | state = new FileManager( conf ).listFile( start ); 96 | break; 97 | 98 | } 99 | 100 | return state.toJSONString(); 101 | 102 | } 103 | 104 | public int getStartIndex () { 105 | 106 | String start = this.request.getParameter( "start" ); 107 | 108 | try { 109 | return Integer.parseInt( start ); 110 | } catch ( Exception e ) { 111 | return 0; 112 | } 113 | 114 | } 115 | 116 | /** 117 | * callback参数验证 118 | */ 119 | public boolean validCallbackName ( String name ) { 120 | 121 | if ( name.matches( "^[a-zA-Z_]+[\\w0-9_]*$" ) ) { 122 | return true; 123 | } 124 | 125 | return false; 126 | 127 | } 128 | 129 | } -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/hunter/ImageHunter.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.hunter; 2 | 3 | import java.net.HttpURLConnection; 4 | import java.net.URL; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import cn.com.lee.common.ueditor.PathFormat; 10 | import cn.com.lee.common.ueditor.define.AppInfo; 11 | import cn.com.lee.common.ueditor.define.BaseState; 12 | import cn.com.lee.common.ueditor.define.MIMEType; 13 | import cn.com.lee.common.ueditor.define.MultiState; 14 | import cn.com.lee.common.ueditor.define.State; 15 | import cn.com.lee.common.ueditor.upload.StorageManager; 16 | 17 | 18 | /** 19 | * 图片抓取器 20 | * @author hancong03@baidu.com 21 | * 22 | */ 23 | public class ImageHunter { 24 | 25 | private String filename = null; 26 | private String savePath = null; 27 | private String rootPath = null; 28 | private List allowTypes = null; 29 | private long maxSize = -1; 30 | private String localSavePathPrefix = null; 31 | 32 | private List filters = null; 33 | 34 | public ImageHunter ( Map conf ) { 35 | 36 | this.filename = (String)conf.get( "filename" ); 37 | this.savePath = (String)conf.get( "savePath" ); 38 | this.rootPath = (String)conf.get( "rootPath" ); 39 | this.maxSize = (Long)conf.get( "maxSize" ); 40 | this.allowTypes = Arrays.asList( (String[])conf.get( "allowFiles" ) ); 41 | this.filters = Arrays.asList( (String[])conf.get( "filter" ) ); 42 | this.localSavePathPrefix = (String) conf.get("localSavePathPrefix"); 43 | 44 | } 45 | 46 | public State capture ( String[] list ) { 47 | 48 | MultiState state = new MultiState( true ); 49 | 50 | for ( String source : list ) { 51 | state.addState( captureRemoteData( source ) ); 52 | } 53 | 54 | return state; 55 | 56 | } 57 | 58 | public State captureRemoteData ( String urlStr ) { 59 | 60 | HttpURLConnection connection = null; 61 | URL url = null; 62 | String suffix = null; 63 | 64 | try { 65 | url = new URL( urlStr ); 66 | 67 | if ( !validHost( url.getHost() ) ) { 68 | return new BaseState( false, AppInfo.PREVENT_HOST ); 69 | } 70 | 71 | connection = (HttpURLConnection) url.openConnection(); 72 | 73 | connection.setInstanceFollowRedirects( true ); 74 | connection.setUseCaches( true ); 75 | 76 | if ( !validContentState( connection.getResponseCode() ) ) { 77 | return new BaseState( false, AppInfo.CONNECTION_ERROR ); 78 | } 79 | 80 | suffix = MIMEType.getSuffix( connection.getContentType() ); 81 | 82 | if ( !validFileType( suffix ) ) { 83 | return new BaseState( false, AppInfo.NOT_ALLOW_FILE_TYPE ); 84 | } 85 | 86 | if ( !validFileSize( connection.getContentLength() ) ) { 87 | return new BaseState( false, AppInfo.MAX_SIZE ); 88 | } 89 | 90 | String savePath = this.getPath( this.savePath, this.filename, suffix ); 91 | String physicalPath = this.localSavePathPrefix + savePath; 92 | String path = physicalPath.substring(0, physicalPath.lastIndexOf("/")); 93 | String picName = physicalPath.substring(physicalPath.lastIndexOf("/")+1, physicalPath.length()); 94 | 95 | State state = StorageManager.saveFileByInputStream( connection.getInputStream(), path, picName ); 96 | 97 | if ( state.isSuccess() ) { 98 | state.putInfo( "url", null); 99 | state.putInfo( "source", urlStr ); 100 | } 101 | 102 | return state; 103 | 104 | } catch ( Exception e ) { 105 | return new BaseState( false, AppInfo.REMOTE_FAIL ); 106 | } 107 | 108 | } 109 | 110 | private String getPath ( String savePath, String filename, String suffix ) { 111 | 112 | return PathFormat.parse( savePath + suffix, filename ); 113 | 114 | } 115 | 116 | private boolean validHost ( String hostname ) { 117 | 118 | return !filters.contains( hostname ); 119 | 120 | } 121 | 122 | private boolean validContentState ( int code ) { 123 | 124 | return HttpURLConnection.HTTP_OK == code; 125 | 126 | } 127 | 128 | private boolean validFileType ( String type ) { 129 | 130 | return this.allowTypes.contains( type ); 131 | 132 | } 133 | 134 | private boolean validFileSize ( int size ) { 135 | return size < this.maxSize; 136 | } 137 | 138 | } 139 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/PathFormat.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.regex.Matcher; 6 | import java.util.regex.Pattern; 7 | 8 | public class PathFormat { 9 | 10 | private static final String TIME = "time"; 11 | private static final String FULL_YEAR = "yyyy"; 12 | private static final String YEAR = "yy"; 13 | private static final String MONTH = "mm"; 14 | private static final String DAY = "dd"; 15 | private static final String HOUR = "hh"; 16 | private static final String MINUTE = "ii"; 17 | private static final String SECOND = "ss"; 18 | private static final String RAND = "rand"; 19 | 20 | private static Date currentDate = null; 21 | 22 | public static String parse ( String input ) { 23 | 24 | Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE ); 25 | Matcher matcher = pattern.matcher(input); 26 | 27 | PathFormat.currentDate = new Date(); 28 | 29 | StringBuffer sb = new StringBuffer(); 30 | 31 | while ( matcher.find() ) { 32 | 33 | matcher.appendReplacement(sb, PathFormat.getString( matcher.group( 1 ) ) ); 34 | 35 | } 36 | 37 | matcher.appendTail(sb); 38 | 39 | return sb.toString(); 40 | } 41 | 42 | /** 43 | * 格式化路径, 把windows路径替换成标准路径 44 | * @param input 待格式化的路径 45 | * @return 格式化后的路径 46 | */ 47 | public static String format ( String input ) { 48 | 49 | return input.replace( "\\", "/" ); 50 | 51 | } 52 | 53 | public static String parse ( String input, String filename ) { 54 | 55 | Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE ); 56 | Matcher matcher = pattern.matcher(input); 57 | String matchStr = null; 58 | 59 | PathFormat.currentDate = new Date(); 60 | 61 | StringBuffer sb = new StringBuffer(); 62 | 63 | while ( matcher.find() ) { 64 | 65 | matchStr = matcher.group( 1 ); 66 | if ( matchStr.indexOf( "filename" ) != -1 ) { 67 | filename = filename.replace( "$", "\\$" ).replaceAll( "[\\/:*?\"<>|]", "" ); 68 | matcher.appendReplacement(sb, filename ); 69 | } else { 70 | matcher.appendReplacement(sb, PathFormat.getString( matchStr ) ); 71 | } 72 | 73 | } 74 | 75 | matcher.appendTail(sb); 76 | 77 | return sb.toString(); 78 | } 79 | 80 | private static String getString ( String pattern ) { 81 | 82 | pattern = pattern.toLowerCase(); 83 | 84 | // time 处理 85 | if ( pattern.indexOf( PathFormat.TIME ) != -1 ) { 86 | return PathFormat.getTimestamp(); 87 | } else if ( pattern.indexOf( PathFormat.FULL_YEAR ) != -1 ) { 88 | return PathFormat.getFullYear(); 89 | } else if ( pattern.indexOf( PathFormat.YEAR ) != -1 ) { 90 | return PathFormat.getYear(); 91 | } else if ( pattern.indexOf( PathFormat.MONTH ) != -1 ) { 92 | return PathFormat.getMonth(); 93 | } else if ( pattern.indexOf( PathFormat.DAY ) != -1 ) { 94 | return PathFormat.getDay(); 95 | } else if ( pattern.indexOf( PathFormat.HOUR ) != -1 ) { 96 | return PathFormat.getHour(); 97 | } else if ( pattern.indexOf( PathFormat.MINUTE ) != -1 ) { 98 | return PathFormat.getMinute(); 99 | } else if ( pattern.indexOf( PathFormat.SECOND ) != -1 ) { 100 | return PathFormat.getSecond(); 101 | } else if ( pattern.indexOf( PathFormat.RAND ) != -1 ) { 102 | return PathFormat.getRandom( pattern ); 103 | } 104 | 105 | return pattern; 106 | 107 | } 108 | 109 | private static String getTimestamp () { 110 | return System.currentTimeMillis() + ""; 111 | } 112 | 113 | private static String getFullYear () { 114 | return new SimpleDateFormat( "yyyy" ).format( PathFormat.currentDate ); 115 | } 116 | 117 | private static String getYear () { 118 | return new SimpleDateFormat( "yy" ).format( PathFormat.currentDate ); 119 | } 120 | 121 | private static String getMonth () { 122 | return new SimpleDateFormat( "MM" ).format( PathFormat.currentDate ); 123 | } 124 | 125 | private static String getDay () { 126 | return new SimpleDateFormat( "dd" ).format( PathFormat.currentDate ); 127 | } 128 | 129 | private static String getHour () { 130 | return new SimpleDateFormat( "HH" ).format( PathFormat.currentDate ); 131 | } 132 | 133 | private static String getMinute () { 134 | return new SimpleDateFormat( "mm" ).format( PathFormat.currentDate ); 135 | } 136 | 137 | private static String getSecond () { 138 | return new SimpleDateFormat( "ss" ).format( PathFormat.currentDate ); 139 | } 140 | 141 | private static String getRandom ( String pattern ) { 142 | 143 | int length = 0; 144 | pattern = pattern.split( ":" )[ 1 ].trim(); 145 | 146 | length = Integer.parseInt( pattern ); 147 | 148 | return ( Math.random() + "" ).replace( ".", "" ).substring( 0, length ); 149 | 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/resources/config.json: -------------------------------------------------------------------------------- 1 | /* 前后端通信相关的配置,注释只允许使用多行方式 */ 2 | { 3 | /* 上传图片配置项 */ 4 | "imageActionName": "uploadimage", /* 执行上传图片的action名称 */ 5 | "imageFieldName": "upfile", /* 提交的图片表单名称 */ 6 | "imageMaxSize": 2048000, /* 上传大小限制,单位B */ 7 | "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */ 8 | "imageCompressEnable": true, /* 是否压缩图片,默认是true */ 9 | "imageCompressBorder": 1600, /* 图片压缩最长边限制 */ 10 | "imageInsertAlign": "none", /* 插入的图片浮动方式 */ 11 | "imageUrlPrefix": "", /* 图片访问路径前缀 */ 12 | "localSavePathPrefix":"upload/images/inform", 13 | "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ 14 | /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */ 15 | /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */ 16 | /* {time} 会替换成时间戳 */ 17 | /* {yyyy} 会替换成四位年份 */ 18 | /* {yy} 会替换成两位年份 */ 19 | /* {mm} 会替换成两位月份 */ 20 | /* {dd} 会替换成两位日期 */ 21 | /* {hh} 会替换成两位小时 */ 22 | /* {ii} 会替换成两位分钟 */ 23 | /* {ss} 会替换成两位秒 */ 24 | /* 非法字符 \ : * ? " < > | */ 25 | /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */ 26 | 27 | /* 涂鸦图片上传配置项 */ 28 | "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */ 29 | "scrawlFieldName": "upfile", /* 提交的图片表单名称 */ 30 | "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ 31 | "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */ 32 | "scrawlUrlPrefix": "", /* 图片访问路径前缀 */ 33 | "scrawlInsertAlign": "none", 34 | 35 | /* 截图工具上传 */ 36 | "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */ 37 | "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ 38 | "snapscreenUrlPrefix": "", /* 图片访问路径前缀 */ 39 | "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */ 40 | 41 | /* 抓取远程图片配置 */ 42 | "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"], 43 | "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */ 44 | "catcherFieldName": "source", /* 提交的图片列表表单名称 */ 45 | "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ 46 | "catcherUrlPrefix": "", /* 图片访问路径前缀 */ 47 | "catcherMaxSize": 2048000, /* 上传大小限制,单位B */ 48 | "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */ 49 | /*抓取远程图片是否开启,默认true*/ 50 | "catchRemoteImageEnable": false, 51 | 52 | /* 上传视频配置 */ 53 | "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */ 54 | "videoFieldName": "upfile", /* 提交的视频表单名称 */ 55 | "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ 56 | "videoUrlPrefix": "", /* 视频访问路径前缀 */ 57 | "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */ 58 | "videoAllowFiles": [ 59 | ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", 60 | ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */ 61 | 62 | /* 上传文件配置 */ 63 | "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */ 64 | "fileFieldName": "upfile", /* 提交的文件表单名称 */ 65 | "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ 66 | "fileUrlPrefix": "", /* 文件访问路径前缀 */ 67 | "fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */ 68 | "fileAllowFiles": [ 69 | ".png", ".jpg", ".jpeg", ".gif", ".bmp", 70 | ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", 71 | ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", 72 | ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", 73 | ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" 74 | ], /* 上传文件格式显示 */ 75 | 76 | /* 列出指定目录下的图片 */ 77 | "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */ 78 | "imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */ 79 | "imageManagerListSize": 20, /* 每次列出文件数量 */ 80 | "imageManagerUrlPrefix": "", /* 图片访问路径前缀 */ 81 | "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */ 82 | "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */ 83 | 84 | /* 列出指定目录下的文件 */ 85 | "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */ 86 | "fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */ 87 | "fileManagerUrlPrefix": "", /* 文件访问路径前缀 */ 88 | "fileManagerListSize": 20, /* 每次列出文件数量 */ 89 | "fileManagerAllowFiles": [ 90 | ".png", ".jpg", ".jpeg", ".gif", ".bmp", 91 | ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", 92 | ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", 93 | ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", 94 | ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" 95 | ] /* 列出的文件类型 */ 96 | 97 | } -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/upload/StorageManager.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor.upload; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.BufferedOutputStream; 5 | import java.io.ByteArrayOutputStream; 6 | import java.io.File; 7 | import java.io.FileOutputStream; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | import org.apache.commons.io.FileUtils; 14 | import org.springframework.boot.context.properties.ConfigurationProperties; 15 | import org.springframework.stereotype.Component; 16 | 17 | import cn.com.lee.common.ueditor.define.AppInfo; 18 | import cn.com.lee.common.ueditor.define.BaseState; 19 | import cn.com.lee.common.ueditor.define.State; 20 | 21 | @Component 22 | @ConfigurationProperties(prefix="nginx") 23 | public class StorageManager { 24 | public static final int BUFFER_SIZE = 8192; 25 | 26 | private static String fileurl; 27 | 28 | public static String getFileurl() { 29 | return fileurl; 30 | } 31 | 32 | public static void setFileurl(String fileurl) { 33 | StorageManager.fileurl = fileurl; 34 | } 35 | 36 | public static int getBufferSize() { 37 | return BUFFER_SIZE; 38 | } 39 | 40 | public StorageManager() { 41 | } 42 | 43 | public static State saveBinaryFile(byte[] data, String path) { 44 | File file = new File(path); 45 | 46 | State state = valid(file); 47 | 48 | if (!state.isSuccess()) { 49 | return state; 50 | } 51 | 52 | try { 53 | BufferedOutputStream bos = new BufferedOutputStream( 54 | new FileOutputStream(file)); 55 | bos.write(data); 56 | bos.flush(); 57 | bos.close(); 58 | } catch (IOException ioe) { 59 | return new BaseState(false, AppInfo.IO_ERROR); 60 | } 61 | 62 | state = new BaseState(true, file.getAbsolutePath()); 63 | state.putInfo( "size", data.length ); 64 | state.putInfo( "title", file.getName() ); 65 | return state; 66 | } 67 | 68 | public static State saveFileByInputStream(HttpServletRequest request, InputStream is, String path, String picName, 69 | long maxSize) { 70 | 71 | State state = null; 72 | File tmpFile = getTmpFile(); 73 | byte[] dataBuf = new byte[ 2048 ]; 74 | 75 | try { 76 | //转成字节流 77 | ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 78 | int rc = 0; 79 | while ((rc = is.read(dataBuf, 0, 100)) > 0) { 80 | swapStream.write(dataBuf, 0, rc); 81 | } 82 | 83 | dataBuf = swapStream.toByteArray(); 84 | swapStream.flush(); 85 | swapStream.close(); 86 | 87 | if (tmpFile.length() > maxSize) { 88 | tmpFile.delete(); 89 | return new BaseState(false, AppInfo.MAX_SIZE); 90 | } 91 | //调用DFS的存储服务上传文件 92 | //:TODO 93 | /** 94 | * 此处调用文件上传服务,并获取返回结果返回 95 | */ 96 | // UploadResult result = baseFileService.upload(dataBuf, picName, "OM", null); 97 | 98 | boolean success = true; 99 | //如果上传成功 100 | if (success) { 101 | state = new BaseState(true); 102 | state.putInfo( "size", tmpFile.length() ); 103 | state.putInfo( "title", "");//文件名填入此处 104 | state.putInfo( "group", "");//所属group填入此处 105 | state.putInfo( "url", "");//文件访问的url填入此处 106 | tmpFile.delete(); 107 | }else{ 108 | state = new BaseState(false, 4); 109 | tmpFile.delete(); 110 | } 111 | 112 | return state; 113 | 114 | } catch (IOException e) { 115 | } 116 | return new BaseState(false, AppInfo.IO_ERROR); 117 | } 118 | 119 | public static State saveFileByInputStream(InputStream is, String path, String picName) { 120 | State state = null; 121 | 122 | File tmpFile = getTmpFile(); 123 | 124 | byte[] dataBuf = new byte[ 2048 ]; 125 | BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE); 126 | 127 | try { 128 | BufferedOutputStream bos = new BufferedOutputStream( 129 | new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE); 130 | 131 | int count = 0; 132 | while ((count = bis.read(dataBuf)) != -1) { 133 | bos.write(dataBuf, 0, count); 134 | } 135 | bos.flush(); 136 | bos.close(); 137 | 138 | //state = saveTmpFile(tmpFile, path); 139 | //重新将文件转成文件流的方式 140 | // InputStream in = new FileInputStream(tmpFile); 141 | // UploadUtils uploadUtils = new UploadUtils(); 142 | // boolean success = uploadUtils.uploadFile(in, path, picName); 143 | boolean success = true; 144 | 145 | //如果上传成功 146 | if (success) { 147 | state = new BaseState(true); 148 | state.putInfo( "size", tmpFile.length() ); 149 | state.putInfo( "title", tmpFile.getName() ); 150 | tmpFile.delete(); 151 | }else{ 152 | state = new BaseState(false, 4); 153 | tmpFile.delete(); 154 | } 155 | 156 | return state; 157 | } catch (IOException e) { 158 | } 159 | return new BaseState(false, AppInfo.IO_ERROR); 160 | } 161 | 162 | private static File getTmpFile() { 163 | File tmpDir = FileUtils.getTempDirectory(); 164 | String tmpFileName = (Math.random() * 10000 + "").replace(".", ""); 165 | return new File(tmpDir, tmpFileName); 166 | } 167 | 168 | private static State saveTmpFile(File tmpFile, String path) { 169 | State state = null; 170 | File targetFile = new File(path); 171 | 172 | if (targetFile.canWrite()) { 173 | return new BaseState(false, AppInfo.PERMISSION_DENIED); 174 | } 175 | try { 176 | FileUtils.moveFile(tmpFile, targetFile); 177 | } catch (IOException e) { 178 | return new BaseState(false, AppInfo.IO_ERROR); 179 | } 180 | 181 | state = new BaseState(true); 182 | state.putInfo( "size", targetFile.length() ); 183 | state.putInfo( "title", targetFile.getName() ); 184 | 185 | return state; 186 | } 187 | 188 | private static State valid(File file) { 189 | File parentPath = file.getParentFile(); 190 | 191 | if ((!parentPath.exists()) && (!parentPath.mkdirs())) { 192 | return new BaseState(false, AppInfo.FAILED_CREATE_FILE); 193 | } 194 | 195 | if (!parentPath.canWrite()) { 196 | return new BaseState(false, AppInfo.PERMISSION_DENIED); 197 | } 198 | 199 | return new BaseState(true); 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /ueditor-demo/.factorypath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /ueditor-demo/src/main/java/cn/com/lee/common/ueditor/ConfigManager.java: -------------------------------------------------------------------------------- 1 | package cn.com.lee.common.ueditor; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | import java.io.UnsupportedEncodingException; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | import org.json.JSONArray; 14 | import org.json.JSONException; 15 | import org.json.JSONObject; 16 | import org.springframework.util.ResourceUtils; 17 | 18 | import cn.com.lee.common.ueditor.define.ActionMap; 19 | 20 | 21 | 22 | 23 | 24 | /** 25 | * 配置管理器 26 | * @author hancong03@baidu.com 27 | * 28 | */ 29 | public final class ConfigManager { 30 | 31 | private final String rootPath; 32 | private final String originalPath; 33 | private final String contextPath; 34 | private static final String configFileName = "config.json"; 35 | private String parentPath = null; 36 | private JSONObject jsonConfig = null; 37 | // 涂鸦上传filename定义 38 | private final static String SCRAWL_FILE_NAME = "scrawl"; 39 | // 远程图片抓取filename定义 40 | private final static String REMOTE_FILE_NAME = "remote"; 41 | 42 | /* 43 | * 通过一个给定的路径构建一个配置管理器, 该管理器要求地址路径所在目录下必须存在config.properties文件 44 | */ 45 | private ConfigManager ( String rootPath, String contextPath, String uri ) throws FileNotFoundException, IOException { 46 | 47 | rootPath = rootPath.replace( "\\", "/" ); 48 | 49 | this.rootPath = rootPath; 50 | this.contextPath = contextPath; 51 | this.originalPath = "src/main/resources/config.json"; 52 | 53 | this.initEnv(); 54 | 55 | } 56 | 57 | /** 58 | * 配置管理器构造工厂 59 | * @param rootPath 服务器根路径 60 | * @param contextPath 服务器所在项目路径 61 | * @param uri 当前访问的uri 62 | * @return 配置管理器实例或者null 63 | */ 64 | public static ConfigManager getInstance ( String rootPath, String contextPath, String uri ) { 65 | 66 | try { 67 | return new ConfigManager(rootPath, contextPath, uri); 68 | } catch ( Exception e ) { 69 | return null; 70 | } 71 | 72 | } 73 | 74 | // 验证配置文件加载是否正确 75 | public boolean valid () { 76 | return this.jsonConfig != null; 77 | } 78 | 79 | public JSONObject getAllConfig () { 80 | 81 | return this.jsonConfig; 82 | 83 | } 84 | 85 | public Map getConfig ( int type ) throws JSONException { 86 | 87 | Map conf = new HashMap(); 88 | String savePath = null; 89 | String localSavePathPrefix = null; 90 | 91 | switch ( type ) { 92 | 93 | case ActionMap.UPLOAD_FILE: 94 | conf.put( "isBase64", "false" ); 95 | conf.put( "maxSize", this.jsonConfig.getLong( "fileMaxSize" ) ); 96 | conf.put( "allowFiles", this.getArray( "fileAllowFiles" ) ); 97 | conf.put( "fieldName", this.jsonConfig.getString( "fileFieldName" ) ); 98 | savePath = this.jsonConfig.getString( "filePathFormat" ); 99 | break; 100 | 101 | case ActionMap.UPLOAD_IMAGE: 102 | conf.put( "isBase64", "false" ); 103 | conf.put( "maxSize", this.jsonConfig.getLong( "imageMaxSize" ) ); 104 | conf.put( "allowFiles", this.getArray( "imageAllowFiles" ) ); 105 | conf.put( "fieldName", this.jsonConfig.getString( "imageFieldName" ) ); 106 | savePath = this.jsonConfig.getString( "imagePathFormat" ); 107 | localSavePathPrefix = this.jsonConfig.getString("localSavePathPrefix"); 108 | break; 109 | 110 | case ActionMap.UPLOAD_VIDEO: 111 | conf.put( "maxSize", this.jsonConfig.getLong( "videoMaxSize" ) ); 112 | conf.put( "allowFiles", this.getArray( "videoAllowFiles" ) ); 113 | conf.put( "fieldName", this.jsonConfig.getString( "videoFieldName" ) ); 114 | savePath = this.jsonConfig.getString( "videoPathFormat" ); 115 | localSavePathPrefix = this.jsonConfig.getString("localSavePathPrefix"); 116 | break; 117 | 118 | case ActionMap.UPLOAD_SCRAWL: 119 | conf.put( "filename", ConfigManager.SCRAWL_FILE_NAME ); 120 | conf.put( "maxSize", this.jsonConfig.getLong( "scrawlMaxSize" ) ); 121 | conf.put( "fieldName", this.jsonConfig.getString( "scrawlFieldName" ) ); 122 | conf.put( "isBase64", "true" ); 123 | savePath = this.jsonConfig.getString( "scrawlPathFormat" ); 124 | break; 125 | 126 | case ActionMap.CATCH_IMAGE: 127 | conf.put( "filename", ConfigManager.REMOTE_FILE_NAME ); 128 | conf.put( "filter", this.getArray( "catcherLocalDomain" ) ); 129 | conf.put( "maxSize", this.jsonConfig.getLong( "catcherMaxSize" ) ); 130 | conf.put( "allowFiles", this.getArray( "catcherAllowFiles" ) ); 131 | conf.put( "fieldName", this.jsonConfig.getString( "catcherFieldName" ) + "[]" ); 132 | savePath = this.jsonConfig.getString( "catcherPathFormat" ); 133 | localSavePathPrefix = this.jsonConfig.getString("localSavePathPrefix"); 134 | break; 135 | 136 | case ActionMap.LIST_IMAGE: 137 | conf.put( "allowFiles", this.getArray( "imageManagerAllowFiles" ) ); 138 | conf.put( "dir", this.jsonConfig.getString( "imageManagerListPath" ) ); 139 | conf.put( "count", this.jsonConfig.getInt( "imageManagerListSize" ) ); 140 | break; 141 | 142 | case ActionMap.LIST_FILE: 143 | conf.put( "allowFiles", this.getArray( "fileManagerAllowFiles" ) ); 144 | conf.put( "dir", this.jsonConfig.getString( "fileManagerListPath" ) ); 145 | conf.put( "count", this.jsonConfig.getInt( "fileManagerListSize" ) ); 146 | break; 147 | 148 | } 149 | 150 | conf.put( "savePath", savePath ); 151 | conf.put( "localSavePathPrefix", localSavePathPrefix ); 152 | conf.put( "rootPath", this.rootPath ); 153 | 154 | return conf; 155 | 156 | } 157 | 158 | private void initEnv () throws FileNotFoundException, IOException { 159 | 160 | /*File file = new File( this.originalPath ); 161 | 162 | if ( !file.isAbsolute() ) { 163 | file = new File( file.getAbsolutePath() ); 164 | } 165 | //判断是否为本地环境,如果为本地环境,则需要更换json文件的读取路径 166 | if( file.toString().contains(":\\") ){ 167 | file = new File("src/main/resources/config.json"); 168 | if ( !file.isAbsolute() ) { 169 | file = new File( file.getAbsolutePath() ); 170 | } 171 | } 172 | 173 | this.parentPath = file.getParent(); 174 | 175 | String configContent = this.readFile( this.getConfigPath() );*/ 176 | //更改获取配置文件的方式 177 | String configPath = ResourceUtils.getFile("classpath:config.json").getAbsolutePath(); 178 | String configContent = this.readFile( configPath ); 179 | 180 | try{ 181 | JSONObject jsonConfig = new JSONObject( configContent ); 182 | this.jsonConfig = jsonConfig; 183 | } catch ( Exception e ) { 184 | this.jsonConfig = null; 185 | } 186 | 187 | } 188 | 189 | private String getConfigPath () { 190 | return this.parentPath + File.separator + ConfigManager.configFileName; 191 | } 192 | 193 | private String[] getArray ( String key ) throws JSONException { 194 | 195 | JSONArray jsonArray = this.jsonConfig.getJSONArray( key ); 196 | String[] result = new String[ jsonArray.length() ]; 197 | 198 | for ( int i = 0, len = jsonArray.length(); i < len; i++ ) { 199 | result[i] = jsonArray.getString( i ); 200 | } 201 | 202 | return result; 203 | 204 | } 205 | 206 | private String readFile ( String path ) throws IOException { 207 | 208 | StringBuilder builder = new StringBuilder(); 209 | 210 | try { 211 | 212 | InputStreamReader reader = new InputStreamReader( new FileInputStream( path ), "UTF-8" ); 213 | BufferedReader bfReader = new BufferedReader( reader ); 214 | 215 | String tmpContent = null; 216 | 217 | while ( ( tmpContent = bfReader.readLine() ) != null ) { 218 | builder.append( tmpContent ); 219 | } 220 | 221 | bfReader.close(); 222 | 223 | } catch ( UnsupportedEncodingException e ) { 224 | // 忽略 225 | } 226 | 227 | return this.filter( builder.toString() ); 228 | 229 | } 230 | 231 | // 过滤输入字符串, 剔除多行注释以及替换掉反斜杠 232 | private String filter ( String input ) { 233 | 234 | return input.replaceAll( "/\\*[\\s\\S]*?\\*/", "" ); 235 | 236 | } 237 | 238 | } 239 | --------------------------------------------------------------------------------