vue+Java整合UEditor报错后台配置项返回格式出错,上传功能将不能正常使用!

发布于 2022-09-13 01:00:23 字数 10279 浏览 30 评论 0

java+ruoyi框架,Ueditor正常显示,但是在初始化的时候报错“后台配置项返回格式出错,上传功能将不能正常使用!”
后台能打印数据,能读取到config.json,没有报错,config.json中imageUrlPrefix等地址用的是IP地址

1111111
config
/X/XXX/XXXXX/XXXXXX/XXXXXX/XXXXX/target/classes/config.json
\u7b"\u73\u74\u61\u74\u65": "\u6e\u75\u6c\u6c"\u7d
@RequestMapping("/ueditor/ueditorConfig")
    @ResponseBody
    @CrossOrigin
    public void ueditorConfig(HttpServletRequest request, HttpServletResponse response, MultipartFile upfile) {
        System.out.println(1111111);
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = "";
            String actionType = request.getParameter("action");
            System.out.println(actionType);
            if("uploadimage".equals(actionType) && !upfile.isEmpty()){
                // 做图片上传操作
                exec = uploadImage(upfile);

            }else{
                request.setCharacterEncoding( "utf-8" );
                exec = new ActionEnter(request, rootPath).exec();
            }
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            System.out.println(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error("UeditorController#ueditorConfig exception:",e);
        }
    }

{
    "imageActionName": "uploadimage",
    "imageFieldName": "upfile",
    "imageMaxSize": 2048000,
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
    "imageCompressEnable": true,
    "imageCompressBorder": 1600,
    "imageInsertAlign": "none",
    "imageUrlPrefix": "http://xxx:8080/",
    "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "scrawlActionName": "uploadscrawl",
    "scrawlFieldName": "upfile",
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "scrawlMaxSize": 2048000,
    "scrawlUrlPrefix": "",
    "scrawlInsertAlign": "none",


    "snapscreenActionName": "uploadimage",
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "snapscreenUrlPrefix": "http://xxx:8080/",
    "snapscreenInsertAlign": "none",


    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage",
    "catcherFieldName": "source",
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "catcherUrlPrefix": "http://xxx:8080/",
    "catcherMaxSize": 2048000,
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],


    "videoActionName": "uploadvideo",
    "videoFieldName": "upfile",
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}",
    "videoUrlPrefix": "http://xxx:8080/",
    "videoMaxSize": 102400000,
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"],


    "fileActionName": "uploadfile",
    "fileFieldName": "upfile",
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}",
    "fileUrlPrefix": "http://xxx:8080/",
    "fileMaxSize": 51200000,
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ],

    "imageManagerActionName": "listimage",
    "imageManagerListPath": "/ueditor/jsp/upload/image/",
    "imageManagerListSize": 20,
    "imageManagerUrlPrefix": "http://xxx:8080/",
    "imageManagerInsertAlign": "none",
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],


    "fileManagerActionName": "listfile",
    "fileManagerListPath": "/ueditor/jsp/upload/file/",
    "fileManagerUrlPrefix": "http://xxx:8080/",
    "fileManagerListSize": 20,
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ]

}
public final class ConfigManager
{
  private final String rootPath;
  private final String originalPath;
  private final String contextPath;
  private static final String configFileName = "config.json";
  private String parentPath = null;
  private JSONObject jsonConfig = null;
  private static final String SCRAWL_FILE_NAME = "scrawl";
  private static final String REMOTE_FILE_NAME = "remote";
  
  private ConfigManager(String rootPath, String contextPath, String uri)
    throws FileNotFoundException, IOException
  {
    rootPath = rootPath.replace("\\", "/");
    
    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.originalPath="src/main/resources/config.json";
    initEnv();
  }
  
  public static ConfigManager getInstance(String rootPath, String contextPath, String uri)
  {
    try
    {
      return new ConfigManager(rootPath, contextPath, uri);
    }
    catch (Exception e) {}
    return null;
  }
  
  public boolean valid()
  {
    return this.jsonConfig != null;
  }
  
  public JSONObject getAllConfig()
  {
    return this.jsonConfig;
  }
  
  public Map<String, Object> getConfig(int type)
  {
    Map<String, Object> conf = new HashMap();
    String savePath = null;
    switch (type)
    {
    case 4: 
      conf.put("isBase64", "false");
      conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("fileMaxSize")));
      conf.put("allowFiles", getArray("fileAllowFiles"));
      conf.put("fieldName", this.jsonConfig.getString("fileFieldName"));
      savePath = this.jsonConfig.getString("filePathFormat");
      break;
    case 1: 
      conf.put("isBase64", "false");
      conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("imageMaxSize")));
      conf.put("allowFiles", getArray("imageAllowFiles"));
      conf.put("fieldName", this.jsonConfig.getString("imageFieldName"));
      savePath = this.jsonConfig.getString("imagePathFormat");
      break;
    case 3: 
      conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("videoMaxSize")));
      conf.put("allowFiles", getArray("videoAllowFiles"));
      conf.put("fieldName", this.jsonConfig.getString("videoFieldName"));
      savePath = this.jsonConfig.getString("videoPathFormat");
      break;
    case 2: 
      conf.put("filename", "scrawl");
      conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("scrawlMaxSize")));
      conf.put("fieldName", this.jsonConfig.getString("scrawlFieldName"));
      conf.put("isBase64", "true");
      savePath = this.jsonConfig.getString("scrawlPathFormat");
      break;
    case 5: 
      conf.put("filename", "remote");
      conf.put("filter", getArray("catcherLocalDomain"));
      conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("catcherMaxSize")));
      conf.put("allowFiles", getArray("catcherAllowFiles"));
      conf.put("fieldName", this.jsonConfig.getString("catcherFieldName") + "[]");
      savePath = this.jsonConfig.getString("catcherPathFormat");
      break;
    case 7: 
      conf.put("allowFiles", getArray("imageManagerAllowFiles"));
      conf.put("dir", this.jsonConfig.getString("imageManagerListPath"));
      conf.put("count", Integer.valueOf(this.jsonConfig.getInt("imageManagerListSize")));
      break;
    case 6: 
      conf.put("allowFiles", getArray("fileManagerAllowFiles"));
      conf.put("dir", this.jsonConfig.getString("fileManagerListPath"));
      conf.put("count", Integer.valueOf(this.jsonConfig.getInt("fileManagerListSize")));
    }
    conf.put("savePath", savePath);
    conf.put("rootPath", this.rootPath);
    
    return conf;
  }
  
  private void initEnv()
    throws FileNotFoundException, IOException
  {
    File file = new File(this.originalPath);
    if (!file.isAbsolute()) {
      file = new File(file.getAbsolutePath());
    }
    this.parentPath = file.getParent();
    
//    String configContent = readFile(getConfigPath());
    String configJsonPath = null;
    try {
      configJsonPath = this.getClass().getClassLoader().getResource("config.json").toURI().getPath();
      System.out.println(configJsonPath);
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    String configContent = this.readFile( configJsonPath );
    try
    {
      JSONObject jsonConfig = new JSONObject(configContent);
      this.jsonConfig = jsonConfig;
    }
    catch (Exception e)
    {
      this.jsonConfig = null;
    }
  }
  
  private String getConfigPath()
  {
    return this.parentPath + File.separator + "config.json";
  }
  
  private String[] getArray(String key)
  {
    JSONArray jsonArray = this.jsonConfig.getJSONArray(key);
    String[] result = new String[jsonArray.length()];
    
    int i = 0;
    for (int len = jsonArray.length(); i < len; i++) {
      result[i] = jsonArray.getString(i);
    }
    return result;
  }
  
  private String readFile(String path)
    throws IOException
  {
    StringBuilder builder = new StringBuilder();
    try
    {
      InputStreamReader reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
      BufferedReader bfReader = new BufferedReader(reader);
      
      String tmpContent = null;
      while ((tmpContent = bfReader.readLine()) != null) {
        builder.append(tmpContent);
      }
      bfReader.close();
    }
    catch (UnsupportedEncodingException localUnsupportedEncodingException) {}
    return filter(builder.toString());
  }
  
  private String filter(String input)
  {
    return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘴硬脾气大 2022-09-20 01:00:23

解决了,返回的json字符串格式不对,在前端ueditor加载的时候会读取到后端@RequestMapping("/ueditor/ueditorConfig")配置,根据if判断走的是
exec = new ActionEnter(request, rootPath).exec();这个方法,之前读取配置返回的参数错了
下面的代码三个if判断,上传图片、上传文件和读取配置

String exec = "";
            String actionType = request.getParameter("action");
            if("uploadimage".equals(actionType) && !upfile.isEmpty()){
                // 做图片上传操作
                exec = uploadImage(upfile);
            }else if("uploadfile".equals(actionType)&&!upfile.isEmpty()){
                exec =uploadFile(upfile);
            }else{
                request.setCharacterEncoding( "utf-8" );
                exec = new ActionEnter(request, rootPath).exec();
            }

看一下这个exec()方法和invoke()方法,当时打断点的时候invoke()方法中第一个if!ActionMap.mapping.containsKey(this.actionType))是true,直接返回了,说明这个map里面不包括这个actionType,这个actionType的值是"config",但是ActionMap这个集合里面一个值都没有,肯定不对,应该没有初始化

public String exec()
  {
    String callbackName = this.request.getParameter("callback");
    if (callbackName != null)
    {
      if (!validCallbackName(callbackName)) {
        return new BaseState(false, 401).toJSONString();
      }
      return callbackName + "(" + invoke() + ");";
    }
    return invoke();
  }
public String invoke()
  {
    if ((this.actionType == null) || (!ActionMap.mapping.containsKey(this.actionType))) {
      return new BaseState(false, 101).toJSONString();
    }
    if ((this.configManager == null) || (!this.configManager.valid())) {
      return new BaseState(false, 102).toJSONString();
    }
    State state = null;
    
    int actionCode = ActionMap.getType(this.actionType);
    
    Map<String, Object> conf = null;
    switch (actionCode)
    {
    case 0: 
      return this.configManager.getAllConfig().toString();
    case 1: 
    case 2: 
    case 3: 
    case 4: 
      conf = this.configManager.getConfig(actionCode);
      state = new Uploader(this.request, conf).doExec();
      break;
    case 5: 
      conf = this.configManager.getConfig(actionCode);
      String[] list = this.request.getParameterValues((String)conf.get("fieldName"));
      state = new ImageHunter(conf).capture(list);
      break;
    case 6: 
    case 7: 
      conf = this.configManager.getConfig(actionCode);
      int start = getStartIndex();
      state = new FileManager(conf).listFile(start);
    }
    return state.toJSONString();
  }

这个是原始文件
image.png
然后对文件进行了修改,actionType传过来的都是小写不带下划线,这里面原始参数都是大写,除了读取配置其它的功能都是自定义方法应该省略了。

public final class ActionMap
{
  public static final Map<String, Integer> mapping = new HashMap() {};
  public static final int CONFIG = 0;
  public static final int UPLOAD_IMAGE = 1;
  public static final int UPLOAD_SCRAWL = 2;
  public static final int UPLOAD_VIDEO = 3;
  public static final int UPLOAD_FILE = 4;
  public static final int CATCH_IMAGE = 5;
  public static final int LIST_FILE = 6;
  public static final int LIST_IMAGE = 7;

  public static int getType(String key)
  {
    return ((Integer)mapping.get(key)).intValue();
  }
  static {
    mapping.put("config",0);
    mapping.put("uploadimage",1);
    mapping.put("uploadscrawl",2);
    mapping.put("uploadvideo",3);
    mapping.put("uploadfile",4);
    mapping.put("catchimage",5);
    mapping.put("listfile",6);
    mapping.put("listimage",7);
  }
}

这个ActionMap等类都是从ueditor-1.1.2.jar包中反编译复制过来的,按理来说这种jar包不会错的,不知道是不是自己之前哪里配置错了
除了读取配置,上传图片和上传文件方法中返回的报文格式都是固定的

private String uploadFile(MultipartFile file) {
        JSONObject jsonResult = null;
        try {
            if(!checkFileSize(file,1,"M")){
                jsonResult = new JSONObject(resultMap("文件大小超过1M", "", 0, "", "", ""));
                return jsonResult.toString();
            }
            String fileName = file.getOriginalFilename();
            String extraName = fileName.substring(fileName.lastIndexOf("."));
            String filePath = RuoYiConfig.getUploadPath();
            String fileName1 = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName1;
            jsonResult = new JSONObject(resultMap("SUCCESS", url, file.getSize(), fileName, fileName, extraName));
        } catch (Exception e) {
            logger.warn("UeditorController#uploadImage exception:", e);
            jsonResult = new JSONObject(resultMap("文件上传失败", "", 0, "", "", ""));
        }
        return jsonResult.toString();
    }

    private String uploadImage(MultipartFile file) {
        JSONObject jsonResult = null;
        try {
            if(!checkFileSize(file,1,"M")){
                jsonResult = new JSONObject(resultMap("文件上传失败,文件大小超过1M", "", 0, "", "", ""));
                return jsonResult.toString();
            }
            String fileName = file.getOriginalFilename();
            String extraName = fileName.substring(fileName.lastIndexOf("."));

            String filePath = RuoYiConfig.getUploadPath();
            String fileName1 = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName1;
            jsonResult = new JSONObject(resultMap("SUCCESS", url, file.getSize(), fileName, fileName, extraName));
        } catch (Exception e) {
            logger.warn("UeditorController#uploadImage exception:", e);
            jsonResult = new JSONObject(resultMap("文件上传失败", "", 0, "", "", ""));
        }
        return jsonResult.toString();
    }

之后出现过跨域问题,但也是配置错了
我这边开始直接在方法上加了@CrossOrigin注解,但还是错了,后来看浏览器控制台报的跨域错误发现路径错了,config.json里的imageUrlPrefix这些url留空就行了,之前看网上其它帖子都会加localhost或者IP


{
    "imageActionName": "uploadimage",
    "imageFieldName": "upfile",
    "imageMaxSize": 2048000,
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
    "imageCompressEnable": true,
    "imageCompressBorder": 1600,
    "imageInsertAlign": "none",
    "imageUrlPrefix": "",
    "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "scrawlActionName": "uploadscrawl",
    "scrawlFieldName": "upfile",
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "scrawlMaxSize": 2048000,
    "scrawlUrlPrefix": "",
    "scrawlInsertAlign": "none",


    "snapscreenActionName": "uploadimage",
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "snapscreenUrlPrefix": "",
    "snapscreenInsertAlign": "none",


    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage",
    "catcherFieldName": "source",
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
    "catcherUrlPrefix": "",
    "catcherMaxSize": 2048000,
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],


    "videoActionName": "uploadvideo",
    "videoFieldName": "upfile",
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}",
    "videoUrlPrefix": "",
    "videoMaxSize": 102400000,
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"],


    "fileActionName": "uploadfile",
    "fileFieldName": "upfile",
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}",
    "fileUrlPrefix": "",
    "fileMaxSize": 51200000,
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ],

    "imageManagerActionName": "listimage",
    "imageManagerListPath": "/ueditor/jsp/upload/image/",
    "imageManagerListSize": 20,
    "imageManagerUrlPrefix": "",
    "imageManagerInsertAlign": "none",
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],


    "fileManagerActionName": "listfile",
    "fileManagerListPath": "/ueditor/jsp/upload/file/",
    "fileManagerUrlPrefix": "",
    "fileManagerListSize": 20,
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ]

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文