SpringMVC 集成 UEditor

UEditor是由百度开发的富文本web编辑器。其后端jsp代码实现的文件保存/读取路径受限于传统文件系统且只能在应用的webapp目录下, 故作出修改。但是暂没有使用官方后端代码,且只实现了图片上传下载功能。

1. 下载

  • 下载地址:http://ueditor.baidu.com/website/download.html, 下载其中的jsp版本
  • 文件解压后目录结构如下所示


    目录结构.png

2. 搭建项目

  • 2.1. 新建一个maven项目

  • 2.2. pom依赖

  
    UTF-8
    1.7
    1.7
    4.11
    4.3.9.RELEASE
    1.3.2
    2.3
    1.6.4
    2.8.7
    1.2.4
    3.0.1
  

  
    
      junit
      junit
      ${junit.version}
      test
    
    
      org.springframework
      spring-context
      ${spring.version}
    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    
    
      com.fasterxml.jackson.core
      jackson-databind
      ${jackson.version}
    
    
        commons-io
        commons-io
        ${commons.io.version}
    
    
        commons-fileupload
        commons-fileupload
        ${fileupload.version}
    
    
      org.slf4j
      slf4j-log4j12
      ${slf4j.version}
    
    
        com.alibaba
        fastjson
        ${fastjson.version}
    
    
        javax.servlet
        javax.servlet-api
        ${servlet.api.version}
    
  
  • 2.3. spring-mvc.xml



    
    
    

        
            
            
            
    
    
    

  • 2.4. applicationContext.xml



    


  • 2.5. 将ueditor下载解压后目录下图目录结构.png第1部分的代码拷贝到项目的webapp下,如下图所示:

    项目结构.jpg

  • 2.6. 将ueditor下载解压后目录下图目录结构.png第2部分config.json的代码拷贝到项目的src/main/resources下,如下图所示:

config.png

3. 前端配置

修改2.4图中的ueditor.config.js的服务器请求路径

 32      // 服务器统一请求接口路径
 33       , serverUrl: URL + "./ueConvert"

4. 后端实现

  • UEditorController.java
package com.github.brandonbai.springmvcueditordemo.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

/**
 * 
 * @author brandonbai
 *
 */
@Controller
public class UEditorController {

    private static final String DIR_NAME = "~/Desktop";
    
    private static final String PREFIX = "/editor/image";
    
    private static final String FILE_SEPARATOR = File.separator;
    
    private static final String PATH_SEPARATOR = "/";
    
    private static final String PATH_FORMAT = "yyyyMMddHHmmss";
    
    private static final String CONFIG_FILE_NAME = "config.json";
    
    private static final String ACTION_NAME_CONFIG = "config";
    
    private static final String ACTION_NAME_UPLOAD_IMAGE = "uploadimage";
    
    private static final Logger logger = LoggerFactory.getLogger(UEditorController.class);

    /**
     * 配置、图片处理
     */
    @RequestMapping("/ueConvert")
    public void ueditorConvert(HttpServletRequest request, HttpServletResponse response, String action,
            MultipartFile upfile) {

        try {
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
            PrintWriter pw = response.getWriter();
            if (ACTION_NAME_CONFIG.equals(action)) {
                String content = readFile(this.getClass().getResource(PATH_SEPARATOR).getPath() + CONFIG_FILE_NAME);
                pw.write(content);
            } else if (ACTION_NAME_UPLOAD_IMAGE.equals(action)) {
                Map map = new HashMap(16);
                String time = new SimpleDateFormat(PATH_FORMAT).format(new Date());
                try {
                    String originalFilename = upfile.getOriginalFilename();
                    String type = originalFilename.substring(originalFilename.lastIndexOf("."));
                    String dirName = DIR_NAME + PREFIX + FILE_SEPARATOR + time;
                    File dir = new File(dirName);
                    if(!dir.exists() || !dir.isDirectory()) {
                        dir.mkdirs();
                    }
                    String fileName = dirName + FILE_SEPARATOR + originalFilename;
                    upfile.transferTo(new File(fileName));
                    map.put("state", "SUCCESS");
                    map.put("original", originalFilename);
                    map.put("size", upfile.getSize());
                    map.put("title", fileName);
                    map.put("type", type);
                    map.put("url", "." + PREFIX + PATH_SEPARATOR + time + PATH_SEPARATOR + originalFilename);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("upload file error", e);
                    map.put("state", "error");
                }
                response.setHeader("Content-Type", "application/json");
                pw.write(JSON.toJSONString(map));
                pw.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 图片读取
     */
    @RequestMapping(PREFIX + "/{time}/{path}.{type}")
    public void ueditorConvert(@PathVariable("time") String time, @PathVariable("path") String path,
            @PathVariable("type") String type, HttpServletRequest request, HttpServletResponse response) {
        try (FileInputStream fis = new FileInputStream(DIR_NAME + PREFIX + PATH_SEPARATOR + time + PATH_SEPARATOR + path + "." + type)) {
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            ServletOutputStream out = response.getOutputStream();
            out.write(data);
            out.close();
        } catch (Exception e) {
            logger.error("read file error", e);
        }

    }

    private String readFile(String path) {

        StringBuilder builder = new StringBuilder();

        try(BufferedReader bfReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"))) {

            String tmpContent = null;

            while ((tmpContent = bfReader.readLine()) != null) {
                builder.append(tmpContent);
            }

            bfReader.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return builder.toString().replaceAll("/\\*[\\s\\S]*?\\*/", "");

    }

}

5.演示

demo.gif

示例代码

https://github.com/brandonbai/springmvc-ueditor-demo

你可能感兴趣的:(SpringMVC 集成 UEditor)