UEditor SpringMVC 图片上传 & 表单提交

1.显示图片插件

标红的为单张上传与多张上传

toolbars: [
    ['bold','simpleupload', 'insertimage', 'insertvideo','justifyleft','justifyright','justifycenter','link','insertimage','inserthtml','fullscreen']
],

toolbars中加入 'simpleupload', 'insertimage' 即可以显示 单张上传与多图上传标签

2.初始化配置

在步骤1中,显示出来这个时候单张上传应该是灰化的并且多张上传会出现:后端配置项没有正常加载,上传插件不能正常使用!

显示如下:

多张图片上传

3.请求config.json文件

不要着急,这是因为初始化的时候UE会根据 ueditor.config.js 这个文件中的统一请求入口

 // 服务器统一请求接口路径
 serverUrl: URL + "jsp/controller.jsp"

去请求 ueditor/jsp/config.json 这个文件,在srpingmvc里面楼主这边过滤了jsp直接请求,所以将这个请求入口改为对应的@controller

// 服务器统一请求接口路径
 serverUrl: "/gearset/upload/ueditor"

后台@controller 代码:

    /*这里将百度的源码下了下来主要是为了看到底是怎么去请求config.json文件的,读取的是哪个路径*/
    import com.baidu.ueditor.ActionEnter;
    
    @RequestMapping(value = "ueditor", method = RequestMethod.GET)
    public @ResponseBody String ueUpload(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
        //这里就是把controller.jsp代码copy下来
        request.setCharacterEncoding( "utf-8" );
        response.setHeader("Content-Type" , "text/html");
        String roolPath = request.getSession().getServletContext().getRealPath("/");
        String configStr = new ActionEnter(request, roolPath).exec();
        return configStr;
    }

通过上面的代码跟踪发现 他这里面读取的是 请求入口的上一层目录(例:楼主这边统一请求入口为 serverUrl: "/gearset/upload/ueditor" 所以它就去 /gearset/upload/ 下面找 config.json 文件 ,所以config.json一定要放对位置)

最后再说一句,如果出现 后端配置项没有正常加载,上传插件不能正常使用! ,不用怀疑一定一定一定是config.json文件没有取到,或者是请求超时!

4.图片上传入口配置

如果上面几个步骤顺利做完的话,恭喜你,你已经完成了40%,接下来我们需要做的就是怎么将图片上传到我们的服务器文件夹

与初始化中请求config.json 文件一样UE会有一个默认的请求参数,如果你不去动他,他将会是默认的 serverUrl+config.json中的图片上传imageActionName


*举例:我们上面已经将 serverUrl改掉了 所以这里是 : "/gearset/upload/ueditor"
再看config.json 文件中 imageActionName :uploadimage,连起来就是 **/gearset/upload/ueditor?action=uploadimage***

显然这样的请求路径不是我们想要的,我们需要将它改写下,那么怎么做呢,通过看UE的文档可以改写这个请求路径

UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;  
UE.Editor.prototype.getActionUrl = function(action) {  
      if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadvideo') {  
          return '/gearset/upload/ue/cms.article';  
      } else {  
          return this._bkGetActionUrl.call(this, action);  
      }  
}  

大意就是如果action为uploadimage 就转而请求 /gearset/upload/ue/cms.article,也就是我们SpringMVC对应的@Controller

5.图片上传代码

/**
     * 上传图片
     * 
     * @param request
     * @param response
     * @param appPath
     * @return
     * @throws IllegalStateException
     * @throws IOException
     * @throws FileUploadException
     */
    @RequestMapping(value = "ue/{appPath:.*}", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> ueUpload(HttpServletRequest request, HttpServletResponse response,
            @PathVariable String appPath) throws IllegalStateException, IOException,
            FileUploadException {

        Map<String, Object> m = new HashMap<String, Object>();
        // 对上传文件夹和临时文件夹进行初始化
        String rootDir = configInfo.getUploadDir();

        String tmpDir = rootDir + "/tmp";
        File tmpDirPath = new File(tmpDir);

        if (ServletFileUpload.isMultipartContent(request)) {
            request.setCharacterEncoding("utf-8");


            DiskFileItemFactory dff = new DiskFileItemFactory();// 创建该对象
            dff.setRepository(tmpDirPath);// 指定上传文件的临时目录
            dff.setSizeThreshold(2 * 1024 * 1024);// 指定在内存中缓存数据大小,单位为byte
            ServletFileUpload sfu = new ServletFileUpload(dff);// 创建该对象
            sfu.setFileSizeMax(1000000000);// 指定单个上传文件的最大尺寸
            sfu.setSizeMax(1000000000);// 指定一次上传多个文件的总尺寸
            FileItemIterator fii = sfu.getItemIterator(request);// 解析request
            // 请求,并返回FileItemIterator集合
            while (fii.hasNext()) {
                FileItemStream fis = fii.next();// 从集合中获得一个文件流
                if (!fis.isFormField() && fis.getName().length() > 0) {// 过滤掉表单中非文件域

                    String filename = fis.getName();

                    String[] FileName = filename.split("\\.");

                    String preFile = FileName[0];
                    String endFile = FileName[1];


                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    String nowdate = sdf.format(date);


                    String newFileName = preFile + "_" + nowdate + "." + endFile;
                    
                    appPath = appPath.trim().replaceAll("\\.", "/");

                    File appDir = new File(rootDir + "/" + appPath);
                    if (!appDir.isDirectory()) {

                        appDir.mkdir();
                    }
                    // 创建按月分类的子文件夹
                    String currentMonth = new DateUnit().getTheFormatDate(new Date(), "yyyyMM");
                    File appSubDir = new File(appDir + "/" + currentMonth);
                    if (!appSubDir.isDirectory()) {
                        appSubDir.mkdir();
                    }

                    String newFilepath = appSubDir + "/" + newFileName;

                    BufferedInputStream in = new BufferedInputStream(fis.openStream());// 获得文件输入流
                    BufferedOutputStream out =
                            new BufferedOutputStream(new FileOutputStream(new File(newFilepath)));// 获得文件输出流
                    Streams.copy(in, out, true);// 开始把文件写到你指定的上传文件夹
                    m.put("path", appPath + "/" + currentMonth + "/");
                    m.put("filename", newFileName);
                    
                    m.put("original", filename);
                    m.put("name", newFileName);
                    m.put("url", appPath + "/" + currentMonth + "/"+newFileName);
                    m.put("state", "SUCCESS");
                    m.put("type", ".jpg");
                    m.put("size", "99697");

                }
            }
        }

        return m;
    }

关于图片上传的代码不做过多阐述,网上一搜一堆,这里主要是map返回的json对象应当包含可选参数url、state、size、type等字段

6.提取UE中img标签 & 结合表单提交

无非就是将图片的path、name等属性提取出来封装到form表单的参数中提交

/*description:取出ueditor里面的图片
             *author:shu.fangjian 
             *date:2016-12-02 
             * */
            
            var root = UE.htmlparser(UE.getEditor('articleContent').getContent(),true);
            var imgs = new Array();
            imgs = root.getNodesByTagName('img');
            
            var ueImg ={};
            for(var i=0;i<imgs.length;i++){
                console.log(imgs[i].getAttr('src'));
                if(!portal.utils.isEmpty(imgs[i].getAttr('alt'))){
                    var url = imgs[i].getAttr('src');
                    var urlArray = imgs[i].getAttr('src').split("/");
                    if(portal.utils.isEmpty(ueImg.oriName)){
                        ueImg.oriName = imgs[i].getAttr('alt');
                        ueImg.newName = urlArray[urlArray.length-1];
                        ueImg.filePath = urlArray[3] +"/"+urlArray[4]+"/";
                    }else{
                        ueImg.oriName += ","+imgs[i].getAttr('alt') ;
                        ueImg.newName += ","+urlArray[urlArray.length-1] ;
                        ueImg.filePath += ","+urlArray[3] +"/"+urlArray[4]+"/";
                    }
                    
                }
                
            }
            /*end*/

最后将ueImg里面的放到你的表单数据里面提交。

欢迎指正 499260459@qq .com

That's End!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值