您的位置:首页 > 编程语言 > Java开发

Spring Boot整合UEditor,解决找不到上传文件的问题

2016-12-05 10:38 956 查看
在实践中如果贸然尝试使用Controller会导致上传文件失败,原因是因为Spring Boot的Request不能强转成为MultipartRequest,只能通过注解请求数据的键作为参数才能获得上传的文件。这里给一个最佳实践,可以不必大幅度修改Spring Boot的配置和UEditor源码,即可快速整合UEditor。

1、第一步,下载UEditor完整源码包,解压缩,把com.baidu.ueditor整个包的源码导入到工程中。

2、第二步,把UEditor的前端静态文件都放在网站的ueditor路径下。

3、第三步,在JSP源码路径中找到config.json,也复制到网站的ueditor路径下。

4、第四步,在项目中写如下的Sevlet类,它可以直接绕过Spring Boot的控制

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
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;

@WebServlet(name = "UEditorServlet", urlPatterns = "/UEditor")
public class UEditorController extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding( "utf-8" );
response.setHeader("Content-Type" , "text/html");
PrintWriter out = response.getWriter();
ServletContext application=this.getServletContext();
String rootPath = application.getRealPath( "/" );

String action = request.getParameter("action");
String result = new ActionEnter( request, rootPath ).exec();
if( action!=null &&
(action.equals("listfile") || action.equals("listimage") ) ){
rootPath = rootPath.replace("\\", "/");
result = result.replaceAll(rootPath, "/");
}
out.write( result );
}

}


5、第五步,修改com.baidu.ueditor下的ConfigManager类

将configFileName的值修改为"ueditor\\config.json"

6、第六步,修改网站路径下的ueditor/ueditor.config.js脚本

找到 , serverUrl: URL +

在后面的值中做修改,改为../UEditor,用来实现前端自动去访问接口的操作。

7、第七步,写一个Controller,打开一个页面,页面的HTML这样写:

<script id="editor" type="text/plain"  style="width:100%;height:300px"></script>
</div>
<script>
$(document).ready(function (){
var ue = UE.getEditor('editor');
})

</script>


8、完成,打开这个Controller的URL,UEditor即可映入眼帘,上传一张图片试试,如果能上传,说明整合成功。

其他说明:用Chrome浏览器时点击上传图片会有几秒钟的延时,原因不详,有待官方解决。

【关于有Tomcat运行时环境和Jetty运行时环境的区别设定】

感谢windlee09网友所提供的信息,经过实践观察,如果Spring Boot的运行方式是直接从main方法运行,那么需要在SpringBoot的Application类上加上@ServletComponentScan注解。如果采用的是maven clean package tomcat7:run,则无需添加该注解,Tomcat会负责搜索注解类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UEditor Java Spring Boot
相关文章推荐