1. 程式人生 > >SpringBoot專案整合Ueditor富文字

SpringBoot專案整合Ueditor富文字

一、官網下載ueditor原始碼(https://ueditor.baidu.com/website/download.html),javaweb專案使用jsp版,解壓後的檔案目錄如下:

  

  二、將原始碼新增到專案中

     1、把ueditor專案的java原始碼複製到自己專案中,修改匯入包名

        

2、把ue的js的原始碼複製新增到自己專案的靜態資原始檔夾static下,將config.json複製到templates:

三、配置圖片上傳的路徑

1、  applicatio.yml上加入圖片上傳路徑結點

  

  java配置:

@Configuration
public class ImageConfig  implements WebMvcConfigurer {
    @Value("${web.upload}")
    private String  path;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("圖片上傳路徑==========="+path);
        //路徑前面要使用file協議,本地路徑使用/分隔
        registry.addResourceHandler("/img/**").addResourceLocations("file:"+path);
    }
}

四、修改Ueditor原始碼:

  1、改寫controller.jsp,使用javad的Contorller實現

@Controller
@RequestMapping("/admin")
public class AdminController  extends BaseController {
    /**
     *  配置ue伺服器統一請求介面路徑http://localhost:8086/admin/ue
     */
    @RequestMapping("/ue")
    public  void configUEditor(HttpServletRequest  request, HttpServletResponse response){
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }

    }
}

 修改ueditor.config.js中 serverUrl的路徑為http://localhost:8086/admin/ue

2、在config.json中新增圖片上傳的伺服器根路徑

  

3、修改java原始碼:

    (1)修改ConfigManage類的getConfigPath()和getConfig方法

	private String getConfigPath () {
		//return this.parentPath + File.separator + ConfigManager.configFileName;
		try {
			//獲取classpath下的config.json路徑
			return Objects.requireNonNull(this.getClass().getClassLoader().getResource(configFileName)).toURI().getPath();
		} catch (URISyntaxException e) {
			return null;
		}
	}

   修改getConfig 方法, 獲取圖片上傳的路徑basePath

     conf.put("basePath",jsonConfig.getString("basePath"));

  


	public Map<String, Object> getConfig ( int type ) throws  JSONException {
		Map<String, Object> conf = new HashMap<String, Object>();
		String savePath = null;
		switch ( type ) {
			case ActionMap.UPLOAD_FILE:
				conf.put( "isBase64", "false" );
				conf.put( "maxSize", this.jsonConfig.getLong( "fileMaxSize" ) );
				conf.put( "allowFiles", this.getArray( "fileAllowFiles" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "fileFieldName" ) );
				savePath = this.jsonConfig.getString( "filePathFormat" );
				break;
			case ActionMap.UPLOAD_IMAGE:
				conf.put( "isBase64", "false" );
				conf.put( "maxSize", this.jsonConfig.getLong( "imageMaxSize" ) );
				conf.put( "allowFiles", this.getArray( "imageAllowFiles" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "imageFieldName" ) );
				savePath = this.jsonConfig.getString( "imagePathFormat" );
				break;
			case ActionMap.UPLOAD_VIDEO:
				conf.put( "maxSize", this.jsonConfig.getLong( "videoMaxSize" ) );
				conf.put( "allowFiles", this.getArray( "videoAllowFiles" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "videoFieldName" ) );
				savePath = this.jsonConfig.getString( "videoPathFormat" );
				break;
				
			case ActionMap.UPLOAD_SCRAWL:
				conf.put( "filename", ConfigManager.SCRAWL_FILE_NAME );
				conf.put( "maxSize", this.jsonConfig.getLong( "scrawlMaxSize" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "scrawlFieldName" ) );
				conf.put( "isBase64", "true" );
				savePath = this.jsonConfig.getString( "scrawlPathFormat" );
				break;
				
			case ActionMap.CATCH_IMAGE:
				conf.put( "filename", ConfigManager.REMOTE_FILE_NAME );
				conf.put( "filter", this.getArray( "catcherLocalDomain" ) );
				conf.put( "maxSize", this.jsonConfig.getLong( "catcherMaxSize" ) );
				conf.put( "allowFiles", this.getArray( "catcherAllowFiles" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "catcherFieldName" ) + "[]" );
				savePath = this.jsonConfig.getString( "catcherPathFormat" );
				break;
				
			case ActionMap.LIST_IMAGE:
				conf.put( "allowFiles", this.getArray( "imageManagerAllowFiles" ) );
				conf.put( "dir", this.jsonConfig.getString( "imageManagerListPath" ) );
				conf.put( "count", this.jsonConfig.getInt( "imageManagerListSize" ) );
				break;
				
			case ActionMap.LIST_FILE:
				conf.put( "allowFiles", this.getArray( "fileManagerAllowFiles" ) );
				conf.put( "dir", this.jsonConfig.getString( "fileManagerListPath" ) );
				conf.put( "count", this.jsonConfig.getInt( "fileManagerListSize" ) );
				break;
				default:
					break;
				
		}

		conf.put("basePath",jsonConfig.getString("basePath"));
		conf.put("savePath", savePath );
		conf.put("rootPath", this.rootPath );
		
		return conf;
		
	}

(2)執行測試載入

 

 (3)修改BinaryUploader,採用SpringMVC框架的解析器multipartResolver

public static final State save(HttpServletRequest request, Map<String, Object> conf) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;
		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
			if(multipartFile==null){
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}
			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");
			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}
			savePath = PathFormat.parse(savePath, originFileName);
			//String physicalPath = (String) conf.get("rootPath") + savePath;
			String  basePath= (String) conf.get("basePath");
			String  physicalPath=basePath+savePath;

			InputStream is = multipartFile.getInputStream();
			State storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize);
			is.close();
			if (storageState.isSuccess()) {
				storageState.putInfo("url", PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}
			return storageState;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);

	}

(4)pom檔案加入圖片上傳所需的jar包依賴

    

 <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
            <scope>compile</scope>
        </dependency>

五、管理後臺使用

<!DOCTYPE html>
<#include "../base.ftl">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>新增商品</title>
    <script type="text/javascript">
        /**建立ue物件*/
        var ue = UE.getEditor('editor');
        ue.ready(function () {
            ue.setContent("《長相思·一重山》");
        });
    </script>

</head>

<body>

<script id="editor" type="text/plain" name="content" style="width:100%;height:800px;"></script>

</body>
</html>