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

硅谷探秘者 3592 0 0

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


猜你喜欢
winhex 编辑器 class 461 winhex 十六进制
算法基础,linux 1087 问题描述springboot在跨域名调用且需要的请求头时报错:AccesstoXMLHttpRequestat'http://ydatestapi.libawall.com
框架 1567 springbootmybatis1.创建maven2.sql件SETNAMESutf8mb4;SETFOREIGN_KEY_CHECKS=0
weblog 2457 使用 this.panel.BackgroundImage=global::WindowsFormsApplication2.Properties.Resources.one; 这样就给一个panel设置了背景
框架 406 :2.3.1.RELEASE,elasticsearch版:7.6.0demo下载参考:springboot+elasticsearchdemo开始前请阅读:elasticsearch官方pom
框架 1126 springboot件与回显资源映射路径配置:packagecom.dzqc.yx.controller
框架 1422 springboot层,官方推荐使用thymeleaf。thymeleaf只是渲染html的一种方式,是一种模板。第一步创建一个maven第二步:修改Jdk版,添加thymeleaf
框架 5553 springboot启动后执行特方法有时需求,需要启动的时候向数据库中查询一下系统属性,或者需要加载某个特的方法。那么在springboot中可以用如下方法实现第一种实现,实现
归档
2018年11月  12 2018年12月  33 2019年01月  28 2019年02月  28 2019年03月  32 2019年04月  27 2019年05月  33 2019年06月  6 2019年07月  12 2019年08月  12 2019年09月  21 2019年10月  8 2019年11月  15 2019年12月  25 2020年01月  9 2020年02月  5 2020年03月  16 2020年04月  4 2020年06月  1 2020年07月  7 2020年08月  13 2020年09月  9 2020年10月  5 2020年12月  3 2021年01月  1 2021年02月  5 2021年03月  7
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo
目录