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就是如果你上传了照片,但是发现上传错了,在编辑器里删除照片,但是在服务器不会删除,就会出现无用照片,暂时还没想到好的解决方法!!!!


 
 


原文地址:https://www.cnblogs.com/liuyuanchen/p/12696902.html

时间: 2024-08-28 08:05:37

jsp+ssm+tomcat配置ueditor(单图片,视频上传)的相关文章

SSM配置Ueditor实现图片的上传&lt;一&gt;

最近想学点新的东西,于是琢磨着用SSM整合Ueditor来实现图片的上传!至于为什么选Ueditor,道理你懂得啦!百度开发的而且开源,能自定义自己想要的内容,版本更新什么的也比较勤快!接下来我准备记录下探索的过程! 1.下载 点击跳转到Ueditor下载界面 你可以到上面的地址下载Ueditor插件,选择UTF-8编码的Jsp版本. 2.构建工程 新建一个Maven工程,首先把ssm框架的基本的东西搭建好,如果你不清楚ssm基本框架,我博客里面有详细的搭建过程可以参考!在这我就直接上图了! 3

将UEditor的图片批量上传抠出来单独使用

在Web项目中,经常有这样一个需求,就是对图片的批量上传,利用form表单的file可以实现图片的上传,但是用户体验不好,而且不支持ajax提交,网上也有很多图片上传插件,有基于javascript的,也有基于flash的,但是给我的感觉,要么用户体验不好,要么收费的,那么能不能有一个比较好的方案呢?那就是Ueditor! UEditor是百度出品的一款富文本编辑器,里面也集成了一个基于Flash的图片上传插件,由于Ueditor是开源的,所以源代码很容易得到,经过我的一番研究,找到了它的图片上

表单-图片浏览上传-单选框(二)

一.图片浏览上传 1.依然[table]标签包含, 2.[input]包含了[type]等于[file]. <table border="1" align="center"> <tr> <td>图片上传</td> <td><input type="file"</td> </tr> <tr> </table>  二.单选框——点击文字不

Tomcat配置虚拟路径,使上传文件与服务器及工程文件分离开

   使用Tomcat虚拟路径可以达到一个怎样的效果呢?简单说你可以把上传的文件放在你想发的任何一个地方,同时可以自己区分 下文件的类型,图片文件专门放一个地方,压缩包文件放另一个地方. 其实如何配置非常简单,这里以window环境来说明! 首先找到tomcat目录下conf目录下的server.xml文件 在server.xml文件中找到<Host></Host> 然后在其中加上这两句              <Context path="/demo/file&

如何利用”七牛云”在UEditor实现图片的上传和浏览

在学习之前,我参考了朋友些的一篇关于这个功能实现的文章,非常不错.大家可以参考:http://www.cnblogs.com/John-Marnoon/p/5818528.html#3501846 里面都写了具体的实现,我也是参照朋友的文章来操作的.现在我重新整理一下实现的步骤: 1 . 注册一个七牛云用户 2.  在七牛云网站中创建一个空间来存储图片,存储区域选择 华东或是 华北,请先记得上传到华东1区的域名为up.qiniu.com.up-z0.qiniu.com和upload.qiniu.

Tomcat配置虚拟路径,使上传文件与服务器分离

遇到问题介绍:项目中头像上传,上传图片到服务器.如果使用tomcat下的目录作为上传图片的路径,则每次重启服务器图片将消失 遇到问题:使用服务器物理磁盘的D:\upload路径存储文件,访问请求路径的不会映射到希望到的请求. 解决:可以使用tomcat的配置文件将某个请求 映射到 物理路径下 ,完成图片的回显. 具体操作:使用Tomcat虚拟路径 1.修改tomcat的配置文件 window环境   首先找到tomcat目录下conf目录下的server.xml文件   在server.xml文

微擎ueditor编辑器图片批量上传顺序混乱的解决方法

上周六有客户反映刚上线的商城管理系统在商品详情页批量上传图片的时候出现图片显示顺序与上传顺序不一致的问题,经排查,发现是编辑器在上传时是按上传完成的顺序插入图片的,即先传完先显示,在网上查了一下,发现很多人都有遇到这个问题,初步认为是ueditor编辑器的bug,于是按照网上的方法去解决,但都没有解决问题,调试查找之后发现网上的解决方法根本不适合微擎的多图上传,因为涉及的文件都没有被调用....无奈只好自己查找,在和同事查找了将近一天之后终于找到了两个相关文件,然后又花了些功夫,最后总算是弄好了

初试“七牛云”--零基础运用七牛云配合UEditor实现图片的上传和浏览(.NET篇)

(注册和建立存储空间就不介绍了,网上一把一把的资料,自己试着点点也能明白) 作为一个成熟的菜鸟,如果遇到一个新问题,第一步当然是先百度一下... 看了N个关于七牛云的使用的帖子,表示还是蒙圈的,看懂了一部分,但是不系统,理解的不连贯,作为一个凡是要弄个特别明白的死脑筋,于是开始从头看是研究文档....(以下都是来自http://developer.qiniu.com/article/index.html#quickstart,经过个人精简,如有不明,详情请参阅文档) 先弄明白原理,才能更好的看懂

SpringMVC+Maven+tomcat配置----3.用Maven编译上传

注意goals的参数设置tomcat6 ---> tomcat:deploy或者tomcat:redeploy,  tomcat7-----> tomcat7:deploy或者tomcat7:redeploy 运行结果: 注意:运行maven build之前必须先启动tomcat 这时到tomcat管理页面查看项目及运行状态: 这时在浏览器中输入http://localhost:8080/mavenDemo就可以访问部署的项目.