jsp+ssm+tomcat配置ueditor(单图片,视频上传)

一、下载ueditor资源

二、减压资源,将ueditor包(我项目里的utf8-jsp)放到项目的WebContent下的js文件夹里。

 

 

 

 

 把ueditor资源里 utf8-jsp\jsp\lib文件夹里的jar包拷贝到项目的lib里。(以idea为例)选择file--->Project Structure-->Libraries。导入ueditor-1.1.2.jar包。

三、在需要使用的ueditor的页面引用下图的js(顺序是固定的

 

 

 在页面添加 <textarea name="titles" id="description"></textarea>标签。

建一个<script>

<script type="text/javascript">

window.onload = function()
{
/* var ue=UE.getEditor("description");*/
var editor =new UE.ui.Editor();
editor.render("description");//创建ueditor富文本编辑器

//根据不同action上传图片和附件
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
if (action == 'uploadImage') {//uploadImage对应后面的config里的配置
        //根据action判断是图片上传还是视频上传
        return '${ctx}/Order/uploadImg.do';

        } else if (action == 'uploadVideo') {
                return '${ctx}/Order/uploadVideo.do';
} else {
return this._bkGetActionUrl.call(this, action);
}
}
};

</script>
四、编辑controller.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" import="com.baidu.ueditor.ActionEnter"  pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%

request.setCharacterEncoding( "utf-8" );
response.setHeader("Content-Type" , "text/html");
String rootPath = application.getRealPath( "/" );
System.out.println(new ActionEnter( request, rootPath ).exec() );

%>
里面的东西不用动,这个主要是用来启用ueditor的。如果不习惯这样可以创建一个controller。例@Controller
@RequestMapping("/upload")
public class uploadController {
@RequestMapping(value="/enter",method=RequestMethod.GET)
public void enterUE(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding( "utf-8" );
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setHeader("Content-Type" , "text/html");
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();
}
}
}
如果出现
import com.baidu.ueditor.ActionEnter; 这个报错说明没用导入ueditor-1.1.2.jar包。或者导入错误(第二部有说明)
ueditor.config.js中配置serverUrl路劲,(如果没用自己创建一个新的controller,serverUrl的路劲就修改为自己的路径)
// 服务器统一请求接口路径(项目名+controller+接口名)getRootPath()是获取项目名的方法.
, serverUrl:getRootPath()+"/upload/enter.do"
五、修改 ueditor.config.js
(1),工具栏,默认工具栏只有一条(我是这样,不知道别人是不是)可用[]来分行工具栏。例如:
 toolbars: [[
'source', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'removeformat',
      'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist',
       'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom'],
    [ 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|'],
['link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'simpleupload'/*, 'insertimage'*/, 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap',
'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|'],
['horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol',
'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
'print', 'preview', 'searchreplace', 'drafts', 'help'
]]
    //我这里分了4行。
配置config.json 路劲在ueditor-->jsp
/* 上传图片配置项 */
"imageActionName": "uploadImage", /* 执行上传图片的action名称 */
"imageFieldName": "upload", /* 提交的图片表单名称 */
"imageMaxSize": 5442880, /* 上传大小限制,单位B */
"imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
"imageCompressEnable": true, /* 是否压缩图片,默认是true */
"imageCompressBorder": 1600, /* 图片压缩最长边限制 */
"imageInsertAlign": "none", /* 插入的图片浮动方式 */
/* "imageUrlPrefix": "http://localhost:8080/hotelm", */ /*图片访问路径前缀 */
"imagePathFormat": "../images/{filename}", /* 上传保存路径,可以自定义保存路径和文件名格式 */

(2)配置上传单图
,imagesUrl:getRootPath()+"/Order/uploadImg.do"//图片上传接口路劲 :项目名+controller+方法名
,imageActionName:"uploadImage"//action名,就是在页面判断上传图片还是视频,然后返回访问路劲的action
,imageFieldName:"upload"//后台接收图片文件的名称
,imageMaxSize:5442880//图片最大上传限制 5MB
,imageUrlPrefix:"" //../images/{filename}//访问路劲前缀,默认http://localhost:8080
,imagePathFormat:"../images/{filename}"//显示图片路劲,(我研究了一下ueditor.all.js源码,貌似这个可以不用,因为我配置了这个路劲但是依旧不显示图片,所以就放弃它了)
 ,imageAllowFiles:[".png", ".jpg", ".jpeg", ".gif", ".bmp"]//上传图片类型判断

后台代码
@ResponseBody
@RequestMapping(value = "uploadImg", method = RequestMethod.POST)
public Object uploadImg(@RequestParam(value = "upload", required = false)MultipartFile upload) throws IOException {
Map<String,Object> path=new HashMap<String,Object>();

if (!upload.isEmpty()) {// 判断上传的文件是否为空
String fileName = upload.getOriginalFilename();// 文件原名称
//获取扩展名称
String ext = fileName.substring(fileName.lastIndexOf("."));
String newName = UUID.randomUUID().toString().replace("-", "") + ext;
System.out.println("上传的文件原名称:" + fileName);
// 判断文件类型
String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
if (type != null) {// 判断文件类型是否为空
if (imgs().contains(type.toLowerCase())) {//判断上传图片类型是否正确(然后前台有判断,但是以防万一还是判断一下)imgs()一个保存了图片类型的list
double fileSize = (double) upload.getSize() / 1024 / 1024;//MB
if (fileSize <= Double.valueOf(5)) {//判断资源是否小于5mb
String pathUrl = System.getProperty("bookdir");//获取项目绝对路劲(需在web.xml配置)
String url = pathUrl + "images";//images是保存图片的文件夹
//要上传的路径(包括存储的绝对路径和文件名.后缀)
File file1 = new File(url + "\\" + newName);
File file2 = new File(url);

judeDirExists(file2);
try {
upload.transferTo(file1);//上传到服务器
path.put("state", "SUCCESS"); //在此处写上错误提示信息,这样当错误的时候就会显示此信息
path.put("url","../images/"+newName);//这个我自己研究的自定义路劲,因为我的照片保存在我项目里WebContent-->images。所以我页面访问图片的路劲可以使用../images/图片名
                  //(也可根据自己的图片路劲返回)  
/* path.put("url",url + "\\" + newName);*///按照ueditor的原本应该返回图片路劲
path.put("title",newName);
path.put("original",newName);
} catch (Exception e) {
path.put("state", "failed"); //在此处写上错误提示信息,这样当错误的时候就会显示此信息
path.put("url","../images/"+newName);//同理上面success
path.put("title",newName);
path.put("original",newName);
}
}
}
}
}
Gson gson=new Gson();
return gson.toJson(path);//需要返回json数据
}
//图片视频类型(不全)
public static Set<String> imgs(){
Set<String> mFileTypes=new HashSet<String>();
mFileTypes.add("jpg");
mFileTypes.add("png");
mFileTypes.add("gif");
mFileTypes.add("tif");
mFileTypes.add("bmp");
//视频或音频类
mFileTypes.add("avi");
mFileTypes.add("mpg");
mFileTypes.add("mov");
mFileTypes.add("mp4");
return mFileTypes;
}

到这里就完了。如果返回了ueditor原本图片路劲,并且config配置上传图片的回去图片路劲都正确还不显示图片,可以调试ueditor-all.js看看图片路劲有没有错误,查找simpleupload单图片上传。
这是图片上传成功回滚
function callback(){
try{
var link, json, loader,
body = (iframe.contentDocument || iframe.contentWindow.document).body,
result = body.innerText || body.textContent || '';
json = (new Function("return " + result))();
/* link = me.options.imageUrlPrefix + json.url;*///这是ueditor原本图片路劲 :前缀+后台返回路劲
if(json.state == 'SUCCESS' && json.url) {
loader = me.document.getElementById(loadingId);
loader.setAttribute('src', json.url);//自定义返回路劲 ../images/图片吗
loader.setAttribute('_src', json.url);
        /*   loader.setAttribute('src', link);//ueditor原配置
        loader.setAttribute('_src', link);*///ueditor原配置

loader.setAttribute('title', json.title || '');
loader.setAttribute('alt', json.original || '');
loader.removeAttribute('id');
domUtils.removeClasses(loader, 'loadingclass');
} else {
showErrorLoader && showErrorLoader(json.state);
}
  图片上传到此结束。
(3)配置视频上传
配置ueditor-config.js
,videoActionName:"uploadVideo"
,videoFieldName:"upload",
videoAllowFiles:[
".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"
]
配置config.json
/*上传视频配置 */
"videoActionName": "uploadVideo", /*执行上传视频的action名称 */
"videoFieldName": "upload", /* 提交的视频表单名称 */
"videoPathFormat": "../upload/{filename}", /*上传保存路径,可以自定义保存路径和文件名格式 */
"videoUrlPrefix": "", /*视频访问路径前缀 */
"videoMaxSize": 12240000, /*上传大小限制,单位B,默认10MB*/
"videoAllowFiles": [
".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"] /* 上传视频格式显示 */

然后就是写后台代码啦,类似于图片上传

对了,如果出现编辑、修改时视频不显示问题。
修改
ueditor-all.js应该在17679行和17683行

 

把 image换成video

ok啦,其实还有一个问题,就是上传有一个bug就是如果你上传了照片,但是发现上传错了,在编辑器里删除照片,但是在服务器不会删除,就会出现无用照片,暂时还没想到好的解决方法!!!!

 



 
 


posted @ 2020-04-14 11:40  六元  阅读(602)  评论(0编辑  收藏  举报