需求:使用wangEditor进行图片上传,上传的图片存储在磁盘中(并非Tomcat项目目录中),上传成功后wangEditor会进行回显,然后可以通过URL来对上传完成的图片进行引用。Tomcat虚拟路径配置
为了让上传的图片放在Tomcat外,不会在项目重新部署的时候被清空,我们需要先配置一下Tomcat的虚拟路径。
配置好虚拟路径之后,我们将上传的图片存到此路径下面,就能通过URL访问到我们的图片了。
Tomcat版本:8.5.3
端口:9090
①打开Tomcat根目录下的/conf/server.xml
②找到Host节点,添加<Context path="/image" docBase="D:\image" reloadable="true" />
注:docBase 就是你要配置的图片存放的真实路径,我这里放在D:\image文件夹下面;
path是虚拟路径,就是你在项目中访问图片的时候所需要的路径,比如我在D:\image文件夹下面有一张图片,名字为 001.png。这时候我在项目里面访问这张图片的URL就是:http://localhost:9090/image/001.png
reloadable为true,代表热部署,就是你上传图片后,不需要重新启动Tomcat,它会自动加载新上传的图片。
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t &quot;%r&quot; %s %b" />
<Context path="/image" docBase="D:\image" reloadable="true" />
</Host>
配置好之后,我们在D:\image目录下放一张图片001.png(直接拷贝进去就行了然后启动Tomcat服务器,输入URL:http://localhost:9090/image/001.png,就能访问到了。
注意事项:在IDEA中,你在项目中使用Tomcat的时候,需要将Deploy applications configured in Tomcat instance这个选项勾选,这样我们上面的配置才会生效。其他编译器应该也会有类似的操作,就不再讲述。
接下来,就使用SpringMVC和wangEditor进行图片上传操作:
首先,引入所需的Jar包:
其中几个Jar包需要注意:
①增加对文件上传的支持:commons-fileupload 这个包还有其依赖包commons-io
②处理JSON数据所需要的Jar包,主要是为了SpringMVC返回数据的时候将数据转为JSON对象:com.fasterxml.jackson.core ,引入这一个依赖,其他两个jar包(com.fasterxml.jackson.annotations和com.fasterxml.jackson.databind)会自动导入。这里要注意Spring的版本和JSON的版本不要差太多,不然可能会出一些奇怪的问题,我这里Spring版本为4.3.16,JSON的版本为2.9.2。
③创建JSON对象所需的Jar包,主要是为了在Java中构造JSON对象返回给wangEditor: org.json
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>4.3.16.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--可能会用到Servlet的原生API-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--Jsp页面中需要使用的JSTL库,以及其依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!--JSON依赖相关-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
</dependencies>
配置SpringMVC,Spring,web.xml
SpringMVC的配置:
①Spring的配置:application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置扫描器,使注解起作用 -->
<context:component-scan base-package="com.bbs"/>
</beans>
②SpringMVC 的配置:springmvc-servlet.xml
这里需要注意的是:mvc:annotation-driven/ 这一个配置:没有这个的话wangEditor会在浏览器的控制台报406,从而接收不到图片的URL,导致图片回显失败。
mvc:annotation-driven会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,这是Spring MVC为@Controller分发请求所必需的,并且提供了数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持读写XML的支持(JAXB)和读写JSON的支持(默认Jackson)等功能。------博客地址:详细解释
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
">
<context:component-scan base-package="com.bbs"/>
<!--配置默认servlet,处理静态资源-->
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
web.xml配置(重要):
加粗部分是对文件上传的支持,如果没有就会抛:
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
异常,会导致文件上传失败
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/*.xml</param-value>
</context-param>
<!--配置统一编码-->
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 对静态资源的配置 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.ico</url-pattern>
<url-pattern>/img/*</url-pattern>
<url-pattern>/image/*</url-pattern>
<url-pattern>/fonts/*</url-pattern>
<url-pattern>/font/*</url-pattern>
</servlet-mapping>
<!--SpringMVC的拦截器-->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--文件上传配置-->
<strong><multipart-config>
<location></strong><strong style="font-family: 'Lucida Console';">/</location>
<max-file-size>2097152</max-file-size>
<max-request-size>4194304</max-request-size>
</multipart-config></strong></servlet><!-- 匹配所有URL --><servlet-mapping><servlet-name>springDispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>
在准备完环境之后,就开始使用wangEditor。
在SpringMVC中写好接收上传图片的代码:
在这之前,需要了解一下对于服务器端返回的JSON对象的格式,wangEditor使用手册有详细的解释
只有按照这个格式返回JSON数据,富文本编辑器才能够接收到图片的引用url,才能进行回显。
{
// errno 即错误代码,0 表示没有错误。
// 如果有错误,errno != 0,可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
"errno": 0,
// data 是一个数组,返回若干图片的线上地址
"data": [
"图片1地址",
"图片2地址", "……" ] }
package com.bbs.web;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.RequestMethod; 9 import org.springframework.web.bind.annotation.RequestParam; 10 import org.springframework.web.bind.annotation.ResponseBody; 11 import org.springframework.web.multipart.MultipartFile; 12 13 import javax.servlet.http.HttpServletRequest; 14 import java.io.BufferedOutputStream; 15 import java.io.File; 16 import java.io.FileOutputStream; 17 import java.io.IOException; 18 import java.util.HashMap; 19 import java.util.Map; 20 21 @Controller 22 @Component 23 public class FileUpload { 24 @RequestMapping(value = "upload",method = RequestMethod.POST) 25 public @ResponseBody 26 String uploads(HttpServletRequest request, @RequestParam("myFileName")MultipartFile file){ 27 String url = null; 28 byte[] bytes = null; 29 String uploadDir = "D:\\image\\"; 30 String fileName = file.getOriginalFilename();//得到上传的文件名 31 String filePath = uploadDir+fileName; 32 BufferedOutputStream bos = null; 33 FileOutputStream fos = null; 34 35 System.out.println(filePath); 36 try { 37 bytes = file.getBytes(); 38 File temp = new File(filePath); 39 if(!temp.exists()){ 40 temp.createNewFile(); 41 } 42 System.out.println(temp.getAbsolutePath()); 43 fos = new FileOutputStream(temp); 44 bos = new BufferedOutputStream(fos); 45 bos.write(bytes); 46 47 }catch (Exception e){ 48 e.printStackTrace(); 49 }finally { 50 if(bos!=null){ 51 try { 52 bos.close(); 53 }catch (IOException e){ 54 e.printStackTrace(); 55 }finally { 56 if (fos!=null){ 57 try { 58 fos.close(); 59 }catch (IOException e){ 60 e.printStackTrace(); 61 } 62 } 63 } 64 } 65 } 66 System.out.println(request.getContextPath()+fileName); 67 //根据wangEditor的服务端接口,造一个JSON对象返回 68 JSONObject json = new JSONObject(); 69 JSONArray array = new JSONArray(); 70 array.put("/image/"+fileName);//将图片的引用url放入JSON返回给富文本编辑器进行回显 71 json.put("errno",0); 72 json.put("data",array); 73 return json.toString(); 74 } 75 }
然后写一下前端页面:
需要准备wangEditor.min.js 这个文件,并引入到你的页面中,
点击https://github.com/wangfupeng1988/wangEditor/releases下载最新版。
进入 release
文件夹下找到 wangEditor.js
或者 wangEditor.min.js
即可
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>论坛首页</title>
<script type="text/javascript" src="js/wangEditor.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<link rel="stylesheet" href="css/wangEditor.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<strong><div id="editor">
</div></strong>
<form action="postData" method="POST" id="data-form">
<input name="data" class="hidden" id="s-editor"/>
</form>
<button class="btn btn-default" id="submit">提交</button>
</body>
<script type="text/javascript" src="js/editor.js"></script>
</html>
editor.js:
这个配置一定要有,我们在后台接收的时候是根据这个
editor.customConfig.uploadFileName = 'myFileName';//可以随意起,但是一定要和SpringMVC的RequestParam一致
editor.customConfig.uploadImgServer = '/BBS/upload';//这里填你上传文件的请求URL
$(function () {
var E = window.wangEditor;
var editor = new E('#editor');
// 自定义菜单配置
editor.customConfig.menus = [
'underline',
'link',
'image',
'emoticon',
'code',
'undo',
'redo'
];
// 下面两个配置,使用其中一个即可显示“上传图片”的tab。但是两者不要同时使用!!!
//editor.customConfig.uploadImgShowBase64 = true ; // 使用 base64 保存图片
<strong>editor.customConfig.uploadImgServer = '/BBS/upload';
</strong>17 editor.customConfig.debug=true;
<strong>editor.customConfig.uploadFileName = 'myFileName';
</strong>19 editor.customConfig.uploadImgHooks = {
success: function (xhr, editor, result) {
// 图片上传并返回结果,图片插入成功之后触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
console.log(result);
}
};
editor.create();
$('#submit').click(function(){
var content = editor.txt.html();
$('#s-editor').val(content);
$('#data-form').submit();
});
});
测试结果:index.html:
选择图片进行上传:
可以查看一下这张图片的引用:
而在D:\image目录下,存在这张图片:
wangEditor的使用手册:使用手册
花了大概两天的时间,踩了好多坑 (:з」∠)。
认真阅读官方文档还是很重要的。
回到
顶部