springboot项目整合ueditor富文本编辑器并自定义上传图片接口

2019 精帖
0 338

1.修改ueditor.config.js配置文件

修改如下配置:serverUrl: "/exam/ueditor/initController"

image.png

2.创建上传文件配置接口

package com.dzqc.exam.bk.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
/**
 * 	自定义ueditor上传文件配置类
 * @author 硅谷探秘者(jia)
 */
@Controller
public class UeditorController {

	@Value("${message.photo_dir}")
    private String photo_dir;
	
	@Value("${message.photo_url}")
    private String photo_url;
	
	/**
	 *	 初始化UEditor上传文件、图片等配置
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/ueditor/initController")
	public void initController(MultipartFile upfile, HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Type", "text/html");

			System.out.println("url : " + request.getRequestURL().toString());
			String value = request.getParameter("action");
			System.out.println("action:" + value);

			// 文件上传的路径
			String result = null;
			if ("config".equals(value)) { //  读取配置文件,将配置文件数据以json格式返回
				String configPath = "/static/js/utf8-jsp/jsp/config.json";//配置文件路径, 相对于classpath
				/**
				 *  返回JOSN数据
				 * {"videoMaxSize":102400000,"videoActionName":"uploadvideo","fileActionName":"uploadfile","fileManagerListPath":"/ueditor/jsp/upload/file/","imageCompressBorder":1600,"imageManagerAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"imageManagerListPath":"/ueditor/jsp/upload/image/","fileMaxSize":51200000,"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"],"fileManagerActionName":"listfile","snapscreenInsertAlign":"none","scrawlActionName":"uploadscrawl","videoFieldName":"upfile","imageCompressEnable":true,"videoUrlPrefix":"","fileManagerUrlPrefix":"","catcherAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"imageManagerActionName":"listimage","snapscreenPathFormat":"/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}","scrawlPathFormat":"/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}","scrawlMaxSize":2048000,"imageInsertAlign":"none","catcherPathFormat":"/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}","catcherMaxSize":2048000,"snapscreenUrlPrefix":"","imagePathFormat":"/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}","imageManagerUrlPrefix":"","scrawlUrlPrefix":"","scrawlFieldName":"upfile","imageMaxSize":2048000,"imageAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"snapscreenActionName":"uploadimage","catcherActionName":"catchimage","fileFieldName":"upfile","fileUrlPrefix":"","imageManagerInsertAlign":"none","catcherLocalDomain":["127.0.0.1","localhost","img.baidu.com"],"filePathFormat":"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}","videoPathFormat":"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}","fileManagerListSize":20,"imageActionName":"uploadimage","imageFieldName":"upfile","imageUrlPrefix":"","scrawlInsertAlign":"none","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"],"catcherUrlPrefix":"","imageManagerListSize":20,"catcherFieldName":"source","videoAllowFiles":[".flv",".swf",".mkv",".avi",".rm",".rmvb",".mpeg",".mpg",".ogg",".ogv",".mov",".wmv",".mp4",".webm",".mp3",".wav",".mid"]}
				 */
				InputStream inStream = UeditorController.class.getResourceAsStream(configPath);
				StringBuilder builder = new StringBuilder();
				try {
					InputStreamReader reader = new InputStreamReader( inStream, "UTF-8" );
					BufferedReader bfReader = new BufferedReader( reader );
					String tmpContent = null;
					while ( ( tmpContent = bfReader.readLine() ) != null ) {
						builder.append( tmpContent );
					}
					bfReader.close();
				} catch ( UnsupportedEncodingException e ) {
					e.printStackTrace();
				}
				// 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
				result =  builder.toString().replaceAll( "/\\*[\\s\\S]*?\\*/", "" ).replaceAll(" ", "");
				System.out.println("result:" + result);
				
			} else if ("uploadimage".equals(value)) {// 上传文件
				// 上传成功后返回的json数据
				/*
				 * {"state": "SUCCESS","original": "Hydrangeas.jpg","size": "595284","title":
				 * "1551927256870045443.jpg","type": ".jpg","url":
				 * "/upload/image/20190307/1551927256870045443.jpg"}
				 */

				String originalFilename = upfile.getOriginalFilename();
				String type = originalFilename.substring(originalFilename.indexOf("."), originalFilename.length()) ;
				long size = upfile.getSize();
				System.out.println(originalFilename);
				System.out.println(size);

				String fileFullName = photo_dir + originalFilename;
				// 图片访问地址(tomcat服务器)
				String url = photo_url + originalFilename ;
				try {
					upfile.transferTo(new File(fileFullName));
					
					Map<String,Object> map = new HashMap<String,Object>() ;
					map.put("state", "SUCCESS") ;
					map.put("original", originalFilename) ;
					map.put("size", size) ;
					map.put("title", originalFilename) ;
					map.put("type", type) ;
					map.put("url", url) ;
					
					result = JSON.toJSONString(map);
					System.out.println("result : " + result);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			PrintWriter writer = response.getWriter();
			writer.write(result);
			writer.flush();
			writer.close();

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

注意:第一次加载是去加载配置文件,其他才是上传文件。

3.用到的配置:在application.yml配置文件中配置

message: 
  photo_dir: E:/upload/
  photo_url: http://localhost:8080/exam/photo/

photo_dir:是上传文件存在磁盘上的路径

photo_url:是返回给客户端的访问路径


4.springboot静态资源映射配置

package com.dzqc.exam.bk.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  
@Configuration
public class MyWebAppPhotoConfigurer implements WebMvcConfigurer {
  
    @Value("${message.photo_dir}")
    private String photo_dir;
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.err.println(photo_dir);
        registry.addResourceHandler("/photo/**").addResourceLocations("file:"+photo_dir);
    }
}


配置ok

s0924204004.png


留言(0)
加载更多
猜你喜欢