UEditor之图片上传如何和真实项目结合
Posted javaTest
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UEditor之图片上传如何和真实项目结合相关的知识,希望对你有一定的参考价值。
1.首先,我们定义一个名为GetConfigServlet的Servlet,真实项目应该是一个Controller,一样的,这个类就是加载后端配置文件类
package com.ay.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.baidu.ueditor.ActionEnter;
/**
* 该类主要是获取配置文件
* @author Ay
* Servlet implementation class GetConfigServlet
*/
@WebServlet("/GetConfigServlet")
public class GetConfigServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetConfigServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//这里就是把controller.jsp代码copy下来
request.setCharacterEncoding( "utf-8" );
response.setHeader("Content-Type" , "text/html");
String roolPath = request.getSession().getServletContext().getRealPath("/");
//记得把config.json放到/Test/WEB-INF/下
String configStr = new ActionEnter(request, roolPath).exec();
System.out.println(roolPath);
response.getWriter().write(configStr);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
下面是我的代码分布图片:
2.修改ueditor.config,把serverUrl的路径改为我们自己写的后端接口路径,也就是GetConfigServlet类
//原来
// 服务器统一请求接口路径
, serverUrl: URL + "jsp/controller.jsp"
//改为
, serverUrl: URL + "GetConfigServlet"
3.上面就可以加载出富文本框了,这里介绍一个js类loadconfig.js:
(function(){
UE.Editor.prototype.loadServerConfig = function(){
var me = this;
setTimeout(function(){
try{
me.options.imageUrl && me.setOpt(‘serverUrl‘, me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, ‘$1controller$2‘));
var configUrl = me.getActionUrl(‘config‘),
isJsonp = utils.isCrossDomainUrl(configUrl);
/* 发出ajax请求 */
me._serverConfigLoaded = false;
configUrl && UE.ajax.request(configUrl,{
‘method‘: ‘GET‘,
‘dataType‘: isJsonp ? ‘jsonp‘:‘‘,
‘onsuccess‘:function(r){
try {
var config = isJsonp ? r:eval("("+r.responseText+")");
utils.extend(me.options, config);
me.fireEvent(‘serverConfigLoaded‘);
me._serverConfigLoaded = true;
} catch (e) {
showErrorMsg(me.getLang(‘loadconfigFormatError‘));
}
},
‘onerror‘:function(){
showErrorMsg(me.getLang(‘loadconfigHttpError‘));
}
});
} catch(e){
showErrorMsg(me.getLang(‘loadconfigError‘));
}
});
function showErrorMsg(msg) {
console && console.error(msg);
//me.fireEvent(‘showMessage‘, {
// ‘title‘: msg,
// ‘type‘: ‘error‘
//});
}
};
UE.Editor.prototype.isServerConfigLoaded = function(){
var me = this;
return me._serverConfigLoaded || false;
};
UE.Editor.prototype.afterConfigReady = function(handler){
if (!handler || !utils.isFunction(handler)) return;
var me = this;
var readyHandler = function(){
handler.apply(me, arguments);
me.removeListener(‘serverConfigLoaded‘, readyHandler);
};
if (me.isServerConfigLoaded()) {
handler.call(me, ‘serverConfigLoaded‘);
} else {
me.addListener(‘serverConfigLoaded‘, readyHandler);
}
};
})();
4.可是有没有发现一个问题,调用服务端的统一接口已经被加载配置文件给占用了,接下来上传文件接口没有了,怎么办呢,怎么办呢,怎么办呢???
其实UEditor官网在第五章已经讲了,看第五章的:
如何自定义请求地址
本文档说明修改请求地址的方法。
应用场景
ueditor 1.4.2+ 推荐使用唯一的请求地址,通过GET参数action指定不同请求类型。
但很多用户都希望使用自己写好的上传地址,下面提供一种解决方法:
由于所有ueditor请求都通过editor对象的getActionUrl方法获取请求地址,可以直接通过复写这个方法实现,例子如下:
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
if (action == ‘uploadimage‘ || action == ‘uploadscrawl‘ || action == ‘uploadimage‘) {
return ‘http://a.b.com/upload.php‘;
} else if (action == ‘uploadvideo‘) {
return ‘http://a.b.com/video.php‘;
} else {
return this._bkGetActionUrl.call(this, action);
}
}
上面是官方文档,只要覆盖掉原型中的getActionUrl即可
5.我们首先再创建一个类:fileUploadServlet.Java,用于处理文件上传的代码
package com.ay.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class fileUploadServlet
*/
@WebServlet("/fileUploadServlet")
public class fileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public fileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
其次修改config.jso配置文件,把imageActionName的值改为上传文件的路径,如下:
/* 上传图片配置项 */
"imageActionName": "fileUploadServlet", /* 执行上传图片的 action名称 */
最后,我们在simpleupload.html上添加如下代码:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title></title>
<script type="text/javascript" charset="utf-8" src="../ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="editor_api.js"></script>
</head>
<body>
<h1>UEditor简单功能</h1>
<!--style给定宽度可以影响编辑器的最终宽度-->
<script type="text/plain" id="myEditor">
<p>这里我可以写一些输入提示</p>
</script>
<script type="text/javascript">
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.getEditor(‘myEditor‘,{
//这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
//toolbars:[[‘FullScreen‘,‘simpleupload‘,‘Source‘, ‘Undo‘, ‘Redo‘,‘Bold‘,‘test‘]],
//focus时自动清空初始化时的内容
autoClearinitialContent:true,
//关闭字数统计
wordCount:false,
//关闭elementPath
elementPathEnabled:false,
//默认的编辑区域高度
initialFrameHeight:300
//更多其他参数,请参考ueditor.config.js中的配置项
});
UE.Editor.prototype.getActionUrl = function(action) {
//这里很重要,很重要,很重要,要和配置中的imageActionName值一样
if (action == ‘fileUploadServlet‘) {
//这里调用后端我们写的图片上传接口
return ‘http://localhost:8081/Test/fileUploadServlet‘;
}else{
return this._bkGetActionUrl.call(this, action);
}
}
</script>
</body>
</html>
图片上传的类:
package com.ay.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class fileUploadServlet
*/
@WebServlet("/fileUploadServlet")
public class fileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public fileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//这里就是我们项目中真实的代码了
//文件上传肯定是post请求
System.out.println("--------图片上传成功---------------");
System.out.println("------------------------------");
System.out.println("--------图片上传成功-----------");
}
}
写到这里基本就完了,可是你有没有发现,有个问题
一般情况下,我们项目的上传接口以及写好了,且返回到前端的json数据也定了,可是Ueditor需要的json格式和我们项目中返回的json数据不一样,怎么办呢?
一般情况下,我们项目的上传接口以及写好了,且返回到前端的json数据也定了,可是Ueditor需要的json格式和我们项目中返回的json数据不一样,怎么办呢?
一般情况下,我们项目的上传接口以及写好了,且返回到前端的json数据也定了,可是Ueditor需要的json格式和我们项目中返回的json数据不一样,怎么办呢?
看下面:
首先,我们看看Ueditor图片上传成功后,返回的json数据
{
"state": "SUCCESS",
"original": "80px - \u526f\u672c (2).jpg",
"size": "13252",
"title": "1465731377326075274.jpg",
"type": ".jpg",
"url": "/ueditor/jsp/upload/image/20160612/1465731377326075274.jpg"
}
也就是说,如果我们调用自己的图片上传接口,返回的json数据改造成Ueditor需要的json数据即可,在哪里改呢
在simpleupload.js的callback中
function callback(){
try{
var link, json, loader,
body = (iframe.contentDocument || iframe.contentWindow.document).body,
result = body.innerText || body.textContent || ‘‘;
//这里result就是我们真实项目返回的json数据
//很简单写个方法,把老的json变成Ueditor需要的json
oldJson = (new Function("return " + result))();
//这个方法是我写的,用来转化
var json = changeDataToJson(json);
link = me.options.imageUrlPrefix + json.url;
if(json.state == ‘SUCCESS‘ && json.url) {
loader = me.document.getElementById(loadingId);
loader.setAttribute(‘src‘, link);
loader.setAttribute(‘_src‘, link);
loader.setAttribute(‘title‘, json.title || ‘‘);
loader.setAttribute(‘alt‘, json.original || ‘‘);
loader.removeAttribute(‘id‘);
domUtils.removeClasses(loader, ‘loadingclass‘);
} else {
showErrorLoader && showErrorLoader(json.state);
}
}catch(er){
showErrorLoader && showErrorLoader(me.getLang(‘simpleupload.loadError‘));
}
form.reset();
domUtils.un(iframe, ‘load‘, callback);
}
/** 自己写的方法,你们可以自己去实现 **/
function changeDataToJson(json){
var object = {"original":‘‘,"size":‘‘,
"state":‘‘,"title":‘‘,"type":‘‘,
"url":‘‘};
var _json = json;
//。。。。。自己真实项目的逻辑
//。。。。。自己真实项目的逻辑
return object;
}
其实,写到这里基本就结束了,可是还有一个问题
就是,一般,我们图片上传,会把图片上传到服务器的某个盘里,比如:C盘 或者D盘,不太会把它放到项目部署目录下,因为一旦项目重新部署,图片就会消失
这就引发一个问题,先看下面能成功的上传和显示的图片,注意到图片是放到 项目的/ueditor/jsp/upload … 目录下,所以没问题
<img src="http://localhost:8081/Test//ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" title="1465731377326075274.jpg" _src="http://localhost:8081/Test//ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" alt="80px - 副本 (2).jpg">
可是,我们真实项目是放到非tomcat目录下,如C,D盘,这时候,是这样的:
<img src="D:/upload/image/20160612/1465731377326075274.jpg" title="1465731377326075274.jpg" _src="http://localhost:8081/Test//ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" alt="80px - 副本 (2).jpg">
如果是这样的或,google浏览器会报:
解决方法是:
该方法是我们真实项目的一个controller层,提供一个方法,获得图片流
/**
* 根据ID获取图片流
*
* @param id
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/{id}/image", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public void image(@PathVariable("id") String id,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
SysAttachment sysAttachment = sysAttachmentService.findById(id);
AssertUtils.checkResourceFound(sysAttachment);
response.setContentType("image/x-png");
response.setCharacterEncoding("UTF-8");
File file = new File(sysAttachment.getPath());
BufferedImage image = ImageIO.read(file);
ImageIO.write(image, sysAttachment.getType(), response.getOutputStream());
}
也就是说,继续通过调用后端的接口,获得图片
这时候,img便签变成,下面的 “xxx/xxx/image” 就是真实项目的controller的映射路径了
<img src="xxx/xxx/image" title="1465731377326075274.jpg" _src="http://localhost:8081/Test//ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" alt="80px - 副本 (2).jpg">
好了,真的结束了…..
最后用一张图片,表达下上面的逻辑:
以上是关于UEditor之图片上传如何和真实项目结合的主要内容,如果未能解决你的问题,请参考以下文章
Ueditor结合七牛云存储上传图片附件和图片在线管理的实现和最新更新