解决spring 类型项目 ueditor富文本编辑器上传图片等文件失败问题

工作中需要用到UEditor编辑文本,在与springMVC进行整合时,出现了一些问题,结果导致,在进行图片上传时出现如下提示:

上网查询了很多相关资料,此处简要记录下,防止以后遇到类似问题。

一种方式是直接修改源码,步骤如下:

1、编写controller 如下(该接口是ueditor前后台交互的统一路径) :
复制代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.test.dcdp.controller;
{captureBefore} [ ]
import java.io.IOException;
import java.io.PrintWriter;
{captureBefore} [ ]
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
{captureBefore} [ ]
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
{captureBefore} [ ]
import com.baidu.ueditor.ActionEnter;
{captureBefore} [ ]
@Controller
@RequestMapping("/ueditor")
public class UeditorController {
{captureBefore} [ ]
    @RequestMapping("/dispatch")
    public void config(HttpServletRequest request,  HttpServletResponse response) {
           // response.setContentType("application/json");
            String rootPath = request.getSession().getServletContext().getRealPath("/");
            response.setHeader("Content-Type" , "text/html");
            try {
                String a = request.getRequestURI();
                    String exec = new ActionEnter(request, rootPath).exec();
                    PrintWriter writer = response.getWriter();
                    writer.write(exec);
                    writer.flush();
                    writer.close();
            } catch (IOException e) {
                    e.printStackTrace();
            }

    }
}

2、修改ueditor的配置文件 ueditor.config.js(指定后台服务器地址),如下所示

修改前:

1
2
3
4
5
6
7
8
9
10
11
12
var URL = window.UEDITOR_HOME_URL || getUEBasePath();

   /**
    * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
    */
   window.UEDITOR_CONFIG = {

       //为编辑器实例添加一个路径,这个不能被注释
       UEDITOR_HOME_URL: URL

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

修改后 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var getRootPath = function (){
       //获取当前网址
       var curWwwPath=window.document.location.href;
       //获取主机地址之后的目录
       var pathName=window.document.location.pathname;

       var pos=curWwwPath.indexOf(pathName);
       //获取主机地址
       var localhostPaht=curWwwPath.substring(0,pos);
       //获取带"/"的项目名,如:/uimcardprj
       var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);

       return(localhostPaht+projectName);
   }
   //获取路径
   var applicationPath = getRootPath();
   var URL = window.UEDITOR_HOME_URL || getUEBasePath();
   var serverURL = applicationPath;

   /**
    * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
    */
   window.UEDITOR_CONFIG = {

       //为编辑器实例添加一个路径,这个不能被注释
       UEDITOR_HOME_URL: URL

       // 服务器统一请求接口路径
       , serverUrl: serverURL + "ueditor/dispatch"

3、修改ueditor源码 ConfigManager.java(指定配置文件路径).

修改前 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
     * 通过一个给定的路径构建一个配置管理器, 该管理器要求地址路径所在目录下必须存在config.properties文件
     */
    private ConfigManager ( String rootPath, String contextPath, String uri ) throws FileNotFoundException, IOException {

        rootPath = rootPath.replace( "\\", "/" );

        this.rootPath = rootPath;
        this.contextPath = contextPath;

        if ( contextPath.length() > 0 ) {
            this.originalPath = this.rootPath + uri.substring( contextPath.length() );
        } else {
            this.originalPath = this.rootPath + uri;
        }

        this.initEnv();

    }

修改后 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
   * 通过一个给定的路径构建一个配置管理器, 该管理器要求地址路径所在目录下必须存在config.properties文件
   */
  private ConfigManager ( String rootPath, String contextPath, String uri ) throws FileNotFoundException, IOException {

      rootPath = rootPath.replace( "\\", "/" );

      this.rootPath = rootPath;
      this.contextPath = contextPath;

      /*if ( contextPath.length() > 0 ) {
          this.originalPath = this.rootPath + uri.substring( contextPath.length() );
      } else {
          this.originalPath = this.rootPath + uri;
      }*/

      this.originalPath = rootPath + "static" + File.separator + "lib" + File.separator +
              "ueditor" + File.separator + "1.4.3" + File.separator + "jsp" + File.separator + "controller.jsp";
      ///EdwManage/src/main/webapp/static/lib/ueditor/1.4.3/jsp/controller.jsp

      this.initEnv();

  }

如上所述,主要修改 originalPath 的路径,否则ueditor的配置文件(ueditor_config.json)路径是错误的(与springMVC整合的情况),之所以向上面那样拼接路径,是因为我的ueditor相关文件拷贝在了(EdwManage/src/main/webapp/static/lib/ueditor/1.4.3/jsp/controller.jsp)路径里。

4、(若未执行该步操作,在选择好图片后,点击上传,将提示 : “未找到上传文件”)由于上传的文件都会被springmvc的文件上传拦截器拦截,包装,这样百度编辑器接收到文件后不能识别文件格式,因此把spring默认的commonsMultiparResolver,替换成我们自己写的commonsMultiparResolver ,并修改配置文件。

重写CommonsMultipartResolver :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 package com.tianwen.dcdp.common;

import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class CommonsMultiparResolver extends CommonsMultipartResolver {

    @Override
      public boolean isMultipart(javax.servlet.http.HttpServletRequest request) {
       String uri = request.getRequestURI();
       System.out.println(uri);
       //过滤使用百度UEditor的URI
       if (uri.indexOf("ueditor/dispatch") > 0) {     //此处拦截路径即为上面编写的controller路径
        System.out.println("commonsMultipartResolver 放行");
        return false;
       }
       System.out.println("commonsMultipartResolver 拦截");
       return super.isMultipart(request);
      }
}

 

修改springMVC配置文件spring-mvc.xml :

1
2
3
4
5
6
7
8
9
10
<!-- 修改为我们重写的CommonsMultiparResolver而不是spring提供的 -->
   <bean id="multipartResolver"
       class="com.tianwen.dcdp.common.CommonsMultiparResolver">
       <!-- 默认编码 -->
       <property name="defaultEncoding" value="utf-8" />
       <!-- 文件大小最大值 -->
       <property name="maxUploadSize" value="10485760000" />
       <!-- 内存中的最大值 -->
       <property name="maxInMemorySize" value="40960" />
   </bean>

5、最后配置上传文件保存目录,修改ueditor配置文件(ueditor_config.json):

修改如下参数(即配置上传文件的URL路径,若配置不正确,富文本编辑器中将不能正确显示上传的图片):

1
2
"imageUrlPrefix": "http://localhost:80/EdwManage", /* 图片访问路径前缀 */
"imagePathFormat": "/static/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */

此处 imagePathFormat 之所以配置为如上格式,是因为springMVC中,指定了static目录下的资源为静态资源(其他路径都会被springMVC拦截)。

文件默认保存的物理路径为: web应用根路径 + imagePathFormat 。

{yyyy}{mm}{dd} : 按天分类保存

{time}{rand:6} : 随机生成文件名

另外还有一种简单的解决办法:

1、新建一web工程(ueditor)。

2、将下载下来的ueditor文件拷贝到新建工程 的webapps目录下,可参考官网介绍。

3、在使用ueditor的工程中,修改ueditor配置文件(ueditor.config.js)如下 :

1
2
3
4
5
6
7
8
9
10
11
12
13
window.UEDITOR_HOME_URL = "http://localhost/ueditor/";
    var URL = window.UEDITOR_HOME_URL || getUEBasePath();

    /**
     * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
     */
    window.UEDITOR_CONFIG = {

        //为编辑器实例添加一个路径,这个不能被注释
        UEDITOR_HOME_URL: URL

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

3、配置上传文件保存路径,修改(ueditor_config.json) :

1
2
"imageUrlPrefix": "http://localhost:80/ueditor", /* 图片访问路径前缀 */
  "imagePathFormat": "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring中实现UEditor图片上传可以参考以下步骤: 1. 在前端Vue代码中配置UEditor富文本编辑器,并对上传图片做出相关设置。 2. 在Spring后端代码中编写图片上传的控制器,处理前端传递的图片文件信息。 3. 在Spring配置文件中配置文件上传的相关参数。 下面是具体的实现方法: 1. 前端代码: 在Vue组件中引入UEditor富文本编辑器,可以使用UEditor官网提供的Vue UEditor Wrapper组件。并在UEditor配置项中设置上传图片的相关参数,如下所示: ``` <template> <div> <vue-ueditor-wrap v-model="content" :config="ueditorConfig" :z-index="100" ></vue-ueditor-wrap> </div> </template> <script> import VueUeditorWrap from 'vue-ueditor-wrap'; export default { components: { VueUeditorWrap }, data () { return { content: '', ueditorConfig: { UEDITOR_HOME_URL: '/static/UEditor/', serverUrl: '/api/upload', maximumWords: 50000, initialFrameWidth: '100%', initialFrameHeight: 500, autoHeightEnabled: false, autoFloatEnabled: false, toolbars: [ ['source', 'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'forecolor', 'backcolor', 'fontfamily', 'fontsize', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', 'touppercase', 'tolowercase', 'link', 'unlink', 'insertimage', 'emotion', 'scrawl', 'music', 'insertvideo', 'attachment', 'map', 'gmap', 'insertcode', 'template', 'background', 'date', 'time', 'spechars', 'searchreplace', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts' ] ] }, }; }, }; </script> ``` 在上述代码中,通过`serverUrl`参数设置了上传图片的后端接口地址为`/api/upload`。 2. 后端控制器代码: 在Spring中,可以通过编写一个控制器方法来实现UEditor上传图片的功能。具体代码如下: ``` @RequestMapping(value = "/api/upload", method = RequestMethod.POST) @ResponseBody public String uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "text/html"); String rootPath = request.getSession().getServletContext().getRealPath("/"); String contextPath = request.getContextPath(); String basePath = rootPath + File.separator + "upload" + File.separator; String savePath = contextPath + "/upload/"; String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"}; String upfile = "upfile"; JSONObject result = new JSONObject(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> iterator = multipartRequest.getFileNames(); while (iterator.hasNext()) { MultipartFile file = multipartRequest.getFile(iterator.next()); if (file != null) { String fileName = file.getOriginalFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); boolean isAllow = false; for (String ext : fileType) { if (ext.equals(fileExt)) { isAllow = true; break; } } if (!isAllow) { result.put("state", "不支持的文件类型!"); return result.toJSONString(); } String newFileName = UUID.randomUUID().toString() + fileExt; File uploadedFile = new File(basePath, newFileName); if (!uploadedFile.getParentFile().exists()) { uploadedFile.getParentFile().mkdirs(); } file.transferTo(uploadedFile); result.put("state", "SUCCESS"); result.put("url", savePath + newFileName); result.put("title", newFileName); result.put("original", fileName); result.put("type", fileExt); result.put("size", file.getSize()); } } return result.toJSONString(); } ``` 3. Spring配置文件: 在Spring的配置文件中,需要配置文件上传的相关参数。具体代码如下: ``` <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> <property name="defaultEncoding" value="UTF-8"/> <property name="resolveLazily" value="true"/> </bean> ``` 其中,`maxUploadSize`参数设置了上传文件的最大大小,单位为字节。 至此,我们就完成了在Spring+Vue中实现UEditor图片上传的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值