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

硅谷探秘者 5185 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 1256 winhex 十六进制
算法基础,linux 4641 问题描述springboot在跨域名调用且需要的请求头时报错:AccesstoXMLHttpRequestat'http://ydatestapi.libawall.com
框架 1962 springboot获取中所有对外提供的信息@ComponentpublicclassTestimplementsApplicationRunner
框架 2780 springbootmybatis1.创建maven2.sql件SETNAMESutf8mb4;SETFOREIGN_KEY_CHECKS=0
weblog 3619 使用 this.panel.BackgroundImage=global::WindowsFormsApplication2.Properties.Resources.one; 这样就给一个panel设置了背景
框架 1576 :2.3.1.RELEASE,elasticsearch版:7.6.0demo下载参考:springboot+elasticsearchdemo开始前请阅读:elasticsearch官方pom
框架 2602 springboot层,官方推荐使用thymeleaf。thymeleaf只是渲染html的一种方式,是一种模板。第一步创建一个maven第二步:修改Jdk版,添加thymeleaf
框架 2238 springboot件与回显资源映射路径配置:packagecom.dzqc.yx.controller
归档
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 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1 2024-04  1 2024-08  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript 加密算法
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。