Spring+Vue整合UEditor富文本实现图片附件上传的方法
作者:silianpan 发布时间:2022-09-27 10:36:13
标签:Spring,Vue,UEditor,图片附件上传
下载UEditor
https://ueditor.baidu.com/website/download.html
下载完整源码和JSP版本
Spring后端集成
1. 解压完整源码,拷贝jsp目录下的java源码,到spring mvc后端
jsp目录下java源码
集成spring mvc后端
2. 配置config.json
解压JSP版本
拷贝jsp目录下config.json
放到java项目的resource目录下,在这里是ueditorConfig.json
配置config.json文件名称,这里是ueditorConfig.json
3. 项目常量配置文件新建upload.properties,也放在resouce目录下,文件内容如下:
#host地址
host=http://localhost:8081/ssm_project
#文件上传服务器地址(ip+端口)
uploadHost=http://localhost:8090/
#普通图片上传保存目录
imagePath = fileUpload/image/
#系统用户头像上传保存目录
headImgPath = fileUpload/image/headImg/
#系统用户默认头像
sysUserDefImg = sysUser-default.jpg
#文本文件上传保存目录
documentPath = fileUpload/document/
#音频文件上传保存目录
soundPath = fileUpload/sound/
#视频文件上传保存目录
videoPath = fileUpload/video/
#ueditor编辑器上传文件保存目录(包括图片、视频、音频、文本等文件)
ueditor = fileUpload/ueditor/
将upload.properties添加到Spring启动配置文件application.xml中,以便后面Controller访问
<!-- 引入数据库配置文件 -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:config.properties</value>
<value>classpath:redis.properties</value>
<value>classpath:upload.properties</value>
</list>
</property>
</bean>
4. 编写工具类UploadUtil.java
package cn.lega.common.util;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class UploadUtil {
/**
* 上传文件
*
* @param request
* @param response
* @param serverPath 服务器地址:(http://172.16.5.102:8090/)
* @param path 文件路径(不包含服务器地址:upload/)
* @return
*/
public static String upload(Client client, MultipartFile file, HttpServletRequest request, HttpServletResponse response, String serverPath, String path) {
// 文件名称生成策略(日期时间+uuid )
UUID uuid = UUID.randomUUID();
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String formatDate = format.format(d);
// 获取文件的扩展名
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
// 文件名
String fileName = formatDate + "-" + uuid + "." + extension;
//相对路径
String relaPath = path + fileName;
// String a = serverPath + path.substring(0, path.lastIndexOf("/"));
// File file2 = new File(a);
// if (!file2.exists()) {
// boolean mkdirs = file2.mkdirs();
// System.out.println(mkdirs);
// }
// 另一台tomcat的URL(真实路径)
String realPath = serverPath + relaPath;
// 设置请求路径
// WebResource resource = client.resource(realPath);
// 发送开始post get put(基于put提交)
// try {
// resource.put(String.class, file.getBytes());
// return fileName + ";" + relaPath + ";" + realPath;
// } catch (IOException e) {
// e.printStackTrace();
// return "";
// }
// 用户目录/root/fileUpload/ueditor
String userDir = System.getProperty("user.home");
String ueditorUploadPath = userDir + File.separator + path;
File file2 = new File(ueditorUploadPath);
if (!file2.exists()) {
file2.mkdirs();
}
String newFilePath = ueditorUploadPath + fileName;
// 保存在本地
File file3 = new File(newFilePath);
try {
FileCopyUtils.copy(file.getBytes(), file3);
return fileName + ";" + relaPath + ";" + realPath;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static String delete(String filePath) {
try {
Client client = new Client();
WebResource resource = client.resource(filePath);
resource.delete();
return "y";
} catch (Exception e) {
e.printStackTrace();
return "n";
}
}
}
5. 编写Controller类UeditorController.java,为前端提供上传接口
package cn.lega.common.controller;
import cn.lega.common.baidu.ueditor.ActionEnter;
import cn.lega.common.util.ResponseUtils;
import cn.lega.common.util.StrUtils;
import cn.lega.common.util.UploadUtil;
import cn.lega.common.web.BaseController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.jersey.api.client.Client;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
/**
* 用于处理关于ueditor插件相关的请求
*
* @author silianpan
*/
@RestController
@CrossOrigin
@RequestMapping("/common/ueditor")
public class UeditorController extends BaseController {
// 后台图片保存地址
@Value("#{configProperties['ueditor']}")
private String ueditor;
@Value("#{configProperties['uploadHost']}")
private String uploadHost; //项目host路径
/**
* ueditor文件上传(上传到外部服务器)
*
* @param request
* @param response
* @param action
*/
@ResponseBody
@RequestMapping(value = "/ueditorUpload.do", method = {RequestMethod.GET, RequestMethod.POST})
public void editorUpload(HttpServletRequest request, HttpServletResponse response, String action) {
response.setContentType("application/json");
String rootPath = request.getSession().getServletContext().getRealPath("/");
try {
if ("config".equals(action)) { // 如果是初始化
String exec = new ActionEnter(request, rootPath).exec();
PrintWriter writer = response.getWriter();
writer.write(exec);
writer.flush();
writer.close();
} else if ("uploadimage".equals(action) || "uploadvideo".equals(action) || "uploadfile".equals(action)) { // 如果是上传图片、视频、和其他文件
try {
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest Murequest = resolver.resolveMultipart(request);
Map<String, MultipartFile> files = Murequest.getFileMap();// 得到文件map对象
// 实例化一个jersey
Client client = new Client();
for (MultipartFile pic : files.values()) {
JSONObject jo = new JSONObject();
long size = pic.getSize(); // 文件大小
String originalFilename = pic.getOriginalFilename(); // 原来的文件名
if (StrUtils.isEmpty(uploadHost) || uploadHost.equals("default")) {
uploadHost = System.getProperty("user.home") + File.separator;
}
String uploadInfo = UploadUtil.upload(client, pic, request, response, uploadHost, ueditor);
if (!"".equals(uploadInfo)) { // 如果上传成功
String[] infoList = uploadInfo.split(";");
jo.put("state", "SUCCESS");
jo.put("original", originalFilename);//原来的文件名
jo.put("size", size); // 文件大小
jo.put("title", infoList[1]); // 随意,代表的是鼠标经过图片时显示的文字
jo.put("type", FilenameUtils.getExtension(pic.getOriginalFilename())); // 文件后缀名
jo.put("url", infoList[2]);// 这里的url字段表示的是上传后的图片在图片服务器的完整地址(http://ip:端口/***/***/***.jpg)
} else { // 如果上传失败
}
ResponseUtils.renderJson(response, jo.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
}
}
// @RequestMapping(value = "/exec")
// public void config(HttpServletRequest request, HttpServletResponse response) {
// // response.setContentType("application/json");
// String rootPath = request.getSession().getServletContext().getRealPath("/");
// response.setHeader("Content-Type" , "text/html");
// try {
// String exec = new ActionEnter(request, rootPath).exec();
// PrintWriter writer = response.getWriter();
// writer.write(exec);
// writer.flush();
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
@RequestMapping(value = "/exec")
@ResponseBody
public String exec(HttpServletRequest request) throws UnsupportedEncodingException {
request.setCharacterEncoding("utf-8");
String rootPath = request.getSession().getServletContext().getRealPath("/");
return new ActionEnter(request, rootPath).exec();
}
@RequestMapping("/ueconfig")
public void getUEConfig(HttpServletRequest request, HttpServletResponse response) {
org.springframework.core.io.Resource res = new ClassPathResource("ueditorConfig.json");
InputStream is = null;
response.setHeader("Content-Type", "text/html");
try {
is = new FileInputStream(res.getFile());
StringBuffer sb = new StringBuffer();
byte[] b = new byte[1024];
int length = 0;
while (-1 != (length = is.read(b))) {
sb.append(new String(b, 0, length, "utf-8"));
}
String result = sb.toString().replaceAll("/\\*(.|[\\r\\n])*?\\*/", "");
JSONObject json = JSON.parseObject(result);
PrintWriter out = response.getWriter();
out.print(json.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Vue前端集成
1. 解压jsp版本,拷贝到Vue前端项目static目录中
2. 前端常量配置
// 静态目录
export const STATIC_PATH = process.env.NODE_ENV === 'production' ? './static/' : '/static/'
// UEditor服务路径,对应UeditorController.java上传接口
export const UEDITOR_SERVER = API_BASEURL + '/common/ueditor/ueditorUpload.do'
3. 安装插件vue-ueditor-wrap
npm install vue-ueditor-wrap
or
yarn add vue-ueditor-wrap
4. 编写组件
<template>
<div>
<component
style="width:100%!important"
:is="currentViewComp"
transition="fade"
transition-mode="out-in"
:config="ueditorConfig"
v-model="formData[item.prop]"
:destroy="true"
@ready="ueReady">
</component>
</div>
</template>
<script>
import VueUeditorWrap from 'vue-ueditor-wrap'
import { STATIC_PATH, UEDITOR_SERVER } from '@/config'
export default {
data() {
return {
currentViewComp: null,
ueditorConfig: {
serverUrl: UEDITOR_SERVER,
UEDITOR_HOME_URL: STATIC_PATH + 'ueditor1_4_3_3/',
initialContent: '',
initialFrameHeight: 400,
initialFrameWidth: '100%',
autoHeightEnabled: false
}
}
},
mounted() {
this.currentViewComp = VueUeditorWrap
},
destroyed() {
this.currentViewComp = null
},
methods: {
ueReady(editorInstance) {
this.$nextTick(() => {
editorInstance.setContent('')
})
}
}
}
</script>
至此,大功告成~
来源:https://segmentfault.com/a/1190000019715256


猜你喜欢
- 本文实例为大家分享了unity实现鼠标跟随的具体代码,供大家参考,具体内容如下需求:当鼠标放到cube上,然后移开鼠标cube会跟随鼠标移动
- 默认情况下Spring Boot使用了内嵌的Tomcat服务器,项目最终被打成jar包运行,每个jar包可以被看作一个独立的Web服务器。传
- import java.util.concurrent.Semaphore;public class ThreeThread {
- ActivityManager.RunningAppProcessInfo类与获取正在运行的应用程序每一个应用程序都会运行在它独立的进程里,
- 有时候我们需要在一个ArrayList的for循环中动态删除元素的需求, 废话不多说看代码List<Integer> list
- 这几天在弄后端管理系统向指定的Android
- Java原生API并不支持为应用程序设置全局热键。要实现全局热键,需要用JNI方式实现,这就涉及到编写C/C++代码,这对于大多数不熟悉C/
- 前言CompletableFuture实现了CompletionStage接口和Future接口,前者是对后者的一个扩展,增加了异步回调、流
- 方法一:1.在pom.xml文件下添加依赖包<dependency><groupId>com.alibaba<
- IEnumerable、ICollection、IList、List之间的区别,本文分别分析了它的实现源码,从而总结出了它们之间的关系和不同
- Android 通过Base64上传图片到服务器之前做上传图片是采用HttpServlet上传,不过用了一下Base64上传图片后,感觉比H
- 最近做项目,ORM 使用的是 MyBatis,为了偷懒,我自然而然的想到了使用 MyBatis Generator(MBG)来生成数据库表对
- 如何在冗长的监控录像中找到关键点?我们知道,监控录像中大部分信息都是没用的,那些信息就等同于一幅静态图像。我们要等待监控的范围内出现异常情况
- 好几天没有跟进Spring MVC的学习了,之前看了点源码都忘的差不多了。这次就跟着之前的问题,继续总结下Spring MVC中的小知识。u
- 目录前言错误实例演示实现ApplicationContextAware接口lookup methodlookup method签名总结前言看
- 发现问题最近在进行压测发现,有一些接口时好时坏,通过sentry日志平台及sky walking平台跟踪发现,用户张三获取到的用户上下文确是
- 加密解密本身并不是难事,问题是在何时去处理?定义一个过滤器,将请求和响应分别拦截下来进行处理也是一个办法,这种方式虽然粗暴,但是灵活,因为可
- 一、# List泛型集合集合是OOP中的一个重要概念,C#中对集合的全面支持更是该语言的精华之一。为什么要用泛型集合?在C# 2.0之前,主
- 原则:1、函数指针,实际上是函数编码后的指令在内存中的首地址,在C++/C中,这个地址可以用函数名直接使用一个函数调用另一个函数的时候,就可
- 本文实例为大家分享了Android自动播放Banner图片轮播的具体代码,供大家参考,具体内容如下先看一下效果图支持本地图片以及网络图片or