UEditor跨域上传图片问题

时间:2022-08-29 08:37:13

前一段项目开始用ueditor编辑器, 因为后面要做集群,所以牵涉到文件服务器,怎样用ue上传图片到文件服务器这方面ue好像做的不太好, 要改源码 ,之前因为只是粗略的试了下忘记记下来导致昨天真正开始做集群的时候就忘了怎么下手, 所以还是记下来吧 ,

配置:本地环境, 文件服务器
语言:java
ue版本: 1.4.3.3 jsp-utf-8版

首先需要在服务器上加入ue, 这里就不多说了,

然后在jsp页面重写getAction方法

UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
if (action == 'uploadimage' || action == 'uploadfile') {
return "http://*.*.*.*:8100/core/fileUpload.doGetRemoteUEFile.do"; //文件服务器保存图片方法
} else {
return this._bkGetActionUrl.call(this, action);
}
};

服务器方法doGetRemoteUEFile


HttpServletResponse response = super.getResponse();
//跨域时需要设置http头信息以返回参数给源地址
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,X_Requested_With");
HttpServletRequest request = super.getRequest();
Map<String, Object> result = new HashMap<String, Object>();
String realPath = request.getSession().getServletContext().getRealPath("/");
InputStream is = null;
FileOutputStream outStream = null;
File outFile = null;
int l = 0;
byte[] buffer = new byte[1024];

String configContent = realPath + "ueditor\\jsp\\config.json";//找到服务器上ue配置的json信息
org.json.JSONObject jsonConfig = new org.json.JSONObject(readFile(configContent));
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;

long maxSize = jsonConfig.getLong("imageMaxSize");

String[] fileNames = wrapper.getFileNames("upfile");
File[] files = wrapper.getFiles("upfile");
if (files[0].length() < maxSize) {
String savePath = (String) jsonConfig.get("imagePathFormat");
savePath = PathFormat.parse(savePath, fileNames[0]);
File tempFile = new File(savePath.substring(0, savePath.lastIndexOf("/")));
if (!tempFile.exists()) {
tempFile.mkdirs();
}
outFile = new File(savePath);

is = new FileInputStream(files[0]);

outStream = new FileOutputStream(outFile);

while ((l = is.read(buffer)) > 0) {
outStream.write(buffer, 0, l);
}
l = 0;
outStream.flush();
outStream.close();
is.close();

//ue自定义请求后端统一格式 这个是uploadImage的返回格式
result.put("state", "SUCCESS");// UEDITOR的规则:不为SUCCESS则显示state的内容
result.put("url", getSubStr(savePath, 2));
result.put("title", fileNames[0]);
result.put("original", fileNames[0]);
}

需要注意的是跨域时ue默认的是H5上传但当不支持H5是会改用flash flash跨域时就需要在服务器根目录加上crossdomain.xml来允许跨域请求