vue + Springboot 前后端分离集成UEditor
UEditor只提供JSP版本的后端入口代码。但是它提供了项目源码,因此我们可以根据业务需求来修改源代码。现在开始集成UEditor 1、下载UEditor官网最新的jsp版本的包,下载完成解压之后得到一个utf8-jsp的文件夹,里面包含的内容如下:除了jsp文件夹和index.html文件外,把所有的文件都复制到前台目录下的static里文件夹里,如下图:2. 将编辑器...
UEditor只提供JSP版本的后端入口代码。但是它提供了项目源码,因此我们可以根据业务需求来修改源代码。
现在开始集成UEditor
1、下载UEditor官网最新的jsp版本的包,下载完成解压之后得到一个utf8-jsp的文件夹,里面包含的内容如下:
除了jsp文件夹和index.html文件外,把所有的文件都复制到前台目录下的static里文件夹里,如下图:
2. 将编辑器封装成一个组件,方便调用,代码如下:
<template>
<div class="edit">
<script id="editor" type="text/plain"></script>
</div>
</template>
<script>
import '../../static/UE/ueditor.config.js'
import '../../static/UE/ueditor.all.js'
import '../../static/UE/lang/zh-cn/zh-cn.js'
export default {
name: 'UEditor',
data () {
return {
editor: null
}
},
props: {
defaultMsg: {
type: String
},
config: {
type: Object
}
},
mounted() {
const _this = this;
this.editor = UE.getEditor('editor', this.config); // 初始化UE
},
methods: {
getUEContent() { // 获取内容方法
return this.editor.getContent()
}
},
destroyed() {
this.editor.destroy();
}
}
</script>
<style lang="scss" scoped>
.edit{
width: 1200px;
margin: auto;
}
</style>
组件的使用:
<template>
<div class="components-container">
<div class="info">UE编辑器示例<br>需要使用编辑器时,调用UE公共组件即可。可设置填充内容defaultMsg,配置信息config(宽度和高度等),可调用组件中获取内容的方法。</div>
<button @click="getUEContent()">获取内容</button>
<div class="editor-container">
<mh-ue :defaultMsg=defaultMsg :config=config ref="ue"></mh-ue>
</div>
</div>
</template>
<script>
import mhUe from '../components/UEditor';
export default {
components: {
mhUe
},
data() {
return {
defaultMsg: '这里是UE测试',
config: {
initialFrameWidth: null,
initialFrameHeight: 350
}
}
},
methods: {
getUEContent() {
let content = this.$refs.ue.getUEContent();
this.$notify({
title: '获取成功,可在控制台查看!',
message: content,
type: 'success'
});
console.log(content)
}
}
};
</script>
<style lang="scss" scoped>
.info{
border-radius: 10px;
line-height: 20px;
padding: 10px;
margin: 10px;
background-color: #ffffff;
}
</style>
前台我们就先做到这里
接下来去配置后台
1.首先从官网上下载源代码,下载之后解压缩,将jsp目录下的src中代码复制到项目中,然后将config.json放到项目的resources中
2. 为UEditor新建一个controller,并写入config映射,代码如下:
@RestController
@RequestMapping("/mh/ueditor")
@CrossOrigin(allowCredentials = "true")
public class UeditorController {
@RequestMapping(value="/config")
public void config(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json");
String rootPath = request.getSession().getServletContext().getRealPath("/");
try {
String exec = new ActionEnter(request, rootPath).exec();
PrintWriter writer = response.getWriter();
writer.write(exec);
writer.flush();
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
3. 修改ConfigManage类的getConfigPath()方法,使其能加载config.json文件,代码如下:
private String getConfigPath () {
// return this.parentPath + File.separator + ConfigManager.configFileName;
/*此部分为手动修改*/
try {
// 需要先转为URI再getPath(),否则项目路径带空格或者带中文则无法读取到文件
return this.getClass().getClassLoader().getResource("config.json").toURI().getPath();
} catch (URISyntaxException e) {
return null;
}
}
4. 转到前台,修改ueditor.config.js
此时已经可以选择图片了,但仍然无法上传图片,那是因为在BinaryUploader类中无法获取到字节流。究其原因,SpringMVC框架对含字节流的request进行了处理,此处传的是处理过的request,故获取不到字节流。此时采用SpringMVC框架的解析器multipartResolver。所以代码修改如下:
package com.baidu.ueditor.upload;
import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import jdk.internal.util.xml.impl.Input;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
public class BinaryUploader {
/**
* 修改BinaryUploader类,解决其无法获得带字节流的request的问题
*/
public static final State save(HttpServletRequest request,
Map<String, Object> conf) {
// FileItemStream fileStream = null;
// boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;
if (!ServletFileUpload.isMultipartContent(request)) {
return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
}
// ServletFileUpload upload = new ServletFileUpload(
// new DiskFileItemFactory());
//
// if ( isAjaxUpload ) {
// upload.setHeaderEncoding( "UTF-8" );
// }
try {
// FileItemIterator iterator = upload.getItemIterator(request);
//
// while (iterator.hasNext()) {
// fileStream = iterator.next();
//
// if (!fileStream.isFormField())
// break;
// fileStream = null;
// }
//
// if (fileStream == null) {
// return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
// }
/*========== 添加的内容 ==========*/
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
if (multipartFile == null) {
return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
}
// 添加结束
String savePath = (String) conf.get("savePath");
// String originFileName = fileStream.getName();
String originFileName = multipartFile.getOriginalFilename(); // 修改的
String suffix = FileType.getSuffixByFilename(originFileName);
originFileName = originFileName.substring(0,
originFileName.length() - suffix.length());
savePath = savePath + suffix;
long maxSize = ((Long) conf.get("maxSize")).longValue();
if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}
savePath = PathFormat.parse(savePath, originFileName);
String physicalPath = (String) conf.get("rootPath") + savePath;
// InputStream is = fileStream.openStream();
InputStream is = multipartFile.getInputStream();
State storageState = StorageManager.saveFileByInputStream(is,
physicalPath, maxSize);
is.close();
if (storageState.isSuccess()) {
storageState.putInfo("url", PathFormat.format(savePath));
storageState.putInfo("type", suffix);
storageState.putInfo("original", originFileName + suffix);
}
return storageState;
// } catch (FileUploadException e) {
// return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
} catch (IOException e) {
}
return new BaseState(false, AppInfo.IO_ERROR);
}
private static boolean validType(String type, String[] allowTypes) {
List<String> list = Arrays.asList(allowTypes);
return list.contains(type);
}
}
5.至此多图片上传已经成功了,但是虽然上传成功了,但却不能展示出来,那是因为它的图片访问路径前缀是前台的路径,而不是后台的访问路径,所以我们要在后台的config.json修改下图片路径前缀,如下图:
至此就可以完整展示出图片了,但是单图片上传依然不行,那是因为出现了iframe跨域的问题,为解决此问题,我将原有的form.submit的表单上传方式,更改为ajax的上传方式;
其代码如下:
/**
* 2018-10-13 改掉了ueditor源码,将本身的单文件上传的方法改为ajax上传,主要目的是为了解决跨域的问题
* @author hqw521@qq.com
*/
domUtils.on(input, 'change', function() {
if(!input.value) return;
var loadingId = 'loading_' + (+new Date()).toString(36);
var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
var allowFiles = me.getOpt('imageAllowFiles');
me.focus();
me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
/!* 判断后端配置是否没有加载成功 *!/
if (!me.getOpt('imageActionName')) {
errorHandler(me.getLang('autoupload.errorLoadConfig'));
return;
}
// 判断文件格式是否错误
var filename = input.value,
fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
return;
}
var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
var action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?' : '&') + params);
var formData = new FormData();
formData.append("upfile", form[0].files[0] );
$.ajax({
url: action,
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false,
success: function (data) {
// data = JSON.parse(data);
var link, loader,
body = (iframe.contentDocument || iframe.contentWindow.document).body,
result = body.innerText || body.textContent || '';
link = me.options.imageUrlPrefix + data.url;
if(data.state == 'SUCCESS' && data.url) {
loader = me.document.getElementById(loadingId);
loader.setAttribute('src', link);
loader.setAttribute('_src', link);
loader.setAttribute('title', data.title || '');
loader.setAttribute('alt', data.original || '');
loader.removeAttribute('id');
domUtils.removeClasses(loader, 'loadingclass');
} else {
showErrorLoader && showErrorLoader(data.state);
}
form.reset();
}
});
function showErrorLoader(title){
if(loadingId) {
var loader = me.document.getElementById(loadingId);
loader && domUtils.remove(loader);
me.fireEvent('showmessage', {
'id': loadingId,
'content': title,
'type': 'error',
'timeout': 4000
});
}
}
});
解决好跨域问题,我们还要引入jQuery文件,依然是这个文件,在24460行左右的代码中,加入下图代码:
至此问题已完美解决.
可是图片上传到哪了,图片被传到了C盘的Tomcat的缓存中C:\Users\hqw\AppData\Local\Temp\tomcat-docbase.112263787422681723.8111,后面的数字每次都是变动的
当我们每次重启Tomcat时,该文件就会被删除,所以我们要把文件存到磁盘中去。
1.修改文件上传路径,在config.json中加入如下代码, 并修改imagePathFormat,
2.打开ConfigManager.java, 加入如下代码
3,打开BinaryUploader.java,修改代码如下:
4.加入路径映射。打开application.yml文件,添加如下代码
web:
upload-path: E:/
spring:
mvc:
static-path-pattern: /**
resources:
static-locations: /META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
运行项目,ueditor图片上传就可以完整的使用了。
更多推荐
所有评论(0)