springboot集成ueditor使用自定义接口上传图片视频

springboot集成ueditor上传图片视频

本文直接简单粗暴的介绍springboot集成百度富文本编辑器ueditor1.4.3版本,并通过自定义接口上传图片和视频,研究了好一会儿,各类帖子看了10几篇,发现坑确实不少,但好歹弄出来了,另本Demo只是一个简单的maven版本SpringbootWeb项目,不是前后分离,所以没有涉及跨域问题的解决,后会更新集成富文本编辑器所遇到的跨域问题

准备

  1. SaveConfig工具类(保存图片,视频到本地)
public class SaveConfig {

	private static String docPath = "D:/A/";

	public static void saveFile(InputStream inputStream, String fileName) {

		OutputStream os = null;
		try {
			byte[] bs = new byte[10240];
			int len;

			File tempFile = new File(docPath);
			if (!tempFile.exists()) {
				tempFile.mkdirs();
			}
			os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
//            System.out.println(tempFile.getPath() + File.separator + fileName);
			// 开始读取
			while ((len = inputStream.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 完毕,关闭所有链接
			try {
				os.close();
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
  1. UeditorConfig工具类(读取ueditor前端所需的config.json)
public class UeditorConfig {

    private JSONObject config;

    public UeditorConfig() {
        StringBuilder config = new StringBuilder();

        try {
//此处即为获取配置文件,因为springboot的原因,目前我只能用流来获取文件内容
            InputStream stream = getClass().getClassLoader().getResourceAsStream("static/config.json");
            BufferedReader buff = new BufferedReader(new InputStreamReader(stream));
            String temp = null;
            while ((temp = buff.readLine()) != null) {
                config.append(temp);
            }
            //把配置文件中的注释去掉
            String configStr = config.toString().replaceAll("/\\*[\\s\\S]*?\\*/", "");
            this.config = JSON.parseObject(configStr);
        } catch (Exception e) {
            this.config = null;
        }
    }

    public JSONObject getConfig() {
        return config;
    }

    public String getConfigStr(String callback) {
    	callback = "123";
        if (this.config == null)
            return (callback + "(读取配置文件失败);");
        return (this.config.toJSONString());
    }

}

  1. WebMvcConfigurer工具类(springboot读取保存到本地的图片,视频)
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
	@Override
	   public void addResourceHandlers(ResourceHandlerRegistry registry) {
	      //和页面有关的静态目录都放在项目的static目录下
	      registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
	      //上传的图片在D盘下的img目录下,访问路径如:http://localhost:8081/img/1.jpg
	      //其中saveFile表示访问的前缀。"file:D:/img/"是文件真实的存储路径
	      registry.addResourceHandler("/saveFile/**").addResourceLocations("file:D:/A/");
	      super.addResourceHandlers(registry);
	   }
}
  1. 在springboot的pom.xml中导入下面的jar包
   <dependency>
   		<groupId>org.json</groupId>
   		<artifactId>json</artifactId>
   	</dependency>
   	<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>

开始

  1. 下载uedtior1.4.3.3版本
    在这里插入图片描述
  2. 把解压后utf8-jsp文件夹里面的所有文件全部放到static下面,同时把jsp里面的config.json剪切到static下面,并删除jsp文件夹(注意看我的static目录结构
    在这里插入图片描述
  3. 新建自定义接口UEditorController
@Controller
@RequestMapping("/ueditor")
public class UEditorController {
	@RequestMapping(value = "/config")
	@ResponseBody
	public Object config(HttpServletRequest request, HttpServletResponse response, String callback, String action)
			throws IOException {
		UeditorConfig ueditorConfig = new UeditorConfig();
		String myresult = ueditorConfig.getConfigStr(callback);
		Map<String, Object> result;
		try {
			switch(action) {
			case "config"://初始化编辑器
				PrintWriter writer = response.getWriter();
				writer.print(myresult);
				writer.flush();
				writer.close();
				break;
			case "uploadimage"://上传图片
				result = uploadFile(request);
				System.out.println(result);
				return result;
			case "uploadvideo"://上传视频
				result = uploadFile(request);
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	//封装上传,回显方法
	private Map<String, Object> uploadFile(HttpServletRequest request) throws IOException {
		String fileName;
		MultipartFile multipartFile;
		String url;
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
		multipartFile = multipartHttpServletRequest.getFile("upfile");// conifg.json里面提交的图片的表单名称
		fileName = multipartFile.getOriginalFilename();
		SaveConfig.saveFile(multipartFile.getInputStream(), fileName);// 调用保存方法保存图片到本地
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("name", fileName);// 新的文件名,偷懒,我懒得改名,想改的自己可以加策略去改
		result.put("originalName", multipartFile.getOriginalFilename());// 原始文件名
		result.put("size", multipartFile.getSize());//文件的长度
		result.put("state", "SUCCESS");//是否成功
		url = "saveFile/" + fileName;//返回的前缀路径 和WebMvcConfigurer里面对应
		result.put("url", url);// 展示图片的请求url
		return result;
	}

}
  1. 修改static下面的ueditor.config.js的第33行服务器统一请求接口路径
    这个ueditor/config要和自定义接口UEditorController里面的请求路径一致
    这个ueditor/config要和自定义接口UEditorController里面的请求路径一致
    改好了,就启动springboot,访问localhost:8080,即可看到Index.html的编辑器页面,同时可以点击图片上传,视频上传
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

备注(工具类需要修改的路径)

  1. SaveConfig的docPath 改成你自己盘的路径
  2. WebMvcConfigurer里面的saveFile要和UEditorController 里面的saveFile保持一致,我不解释了,上面代码里面有注释。
  3. 还有什么问题欢迎留言,一起讨论,一起进步。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值