spring mvc上传文件的简单例子,这有几个需要注意的地方
1.form的enctype=”multipart/form-data” 这个是上传文件必须的
2.需要依赖的jar包(网上找)
具体代码:
1.spring的配置文件
1)springmvc.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- controller配置,自动扫描包内的action -->
<context:component-scan base-package="com.xieyong.bootstrap.controller"></context:component-scan>
<!-- 开启这个配置,spring才能识别@Scheduled注解 -->
<task:annotation-driven />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsps/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置属性转换器 -->
<!-- <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="drug.base.action.conventers.DateConverter"></bean>
<bean class="drug.base.action.conventers.DatetimeConverter"></bean>
<bean class="drug.base.action.conventers.StringTrimConverter"></bean>
</list>
</property>
</bean> -->
<!-- 配置json转换器 -->
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<!-- 文件上传配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
</beans>
2).applicationContext.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:aop="http://www.springframework.org/schema/aop"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd ">
<!-- 配置注解对象所在的包 -->
<context:annotation-config></context:annotation-config>
<!-- 引入properties文件 -->
<context:property-placeholder location="classpath:dbconfig.properties"/>
<!-- 使用dbcp连接池配置,引入外部的配置文件 -->
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 开发阶段建议最大连接数据尽量少,够用即可 -->
<property name="maxActive" value="${jdbc.maxActive}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
</bean>
<!-- 配置事务管理 -->
<!-- 首先配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 事务管理器需从数据源获取连接,才能开启事务,提交事务,回滚事务 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置通知 -->
<tx:advice id="transactionadvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置切面 -->
<aop:config>
<aop:pointcut expression="execution(* com.xieyong.bootstrap.service.*.*(..))" id="mypoint"/>
<aop:advisor advice-ref="transactionadvice" pointcut-ref="mypoint"/>
</aop:config>
</beans>
3).web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>bootstrap</display-name>
<display-name></display-name>
<!-- 监听器,初始化spring容器对象 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 修改spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext.xml,/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>
<!-- 配置springmvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<!-- 屏蔽springmvc自动注册的异常处理器 -->
<init-param>
<param-name>detectAllHandlerExceptionResolvers</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- jfreechart的配置-->
<servlet>
<servlet-name>jfreechart</servlet-name>
<servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jfreechart</servlet-name>
<url-pattern>/jfreechart</url-pattern>
</servlet-mapping>
<!-- post乱码过虑器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 第一种配置*.action,访问以action结尾由DispatcherServlet进行解析
第二种配置 /,所有访问都由DispatcherServlet进行解析,对应静态文件则不需要配置解析
第三种配置/*配置不对-->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
2.后台java代码
@Controller
@RequestMapping("/upload")
public class UploadFileController
{
@RequestMapping("/uploadFile")
@ResponseBody
public String uploadFile(@RequestParam(value = "uploadFile", required = false) MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response){
Map<String,Object> resultMap=new HashMap <String, Object>();
String fileName = uploadFile.getOriginalFilename ();//获取文件上传的名称
String newFileName="";
try
{
//重新命名
if(null!=fileName){
newFileName=UUID.randomUUID ()+fileName.substring (fileName.lastIndexOf ("."));
}
String uploadPath="D:/upload/";//图片上传的目录
File files=new File(uploadPath,newFileName);
if(!files.exists ()){
files.mkdirs ();
}
uploadFile.transferTo (files);
resultMap.put("fileAdress","/upload/"+newFileName);
resultMap.put("uploadFlag",true);
}
catch (Exception e)
{
resultMap.put("uploadFlag",false);
//记日志
}
String json=JSONObject.fromObject (resultMap).toString ();
writeJson(json,response);
return null;
}
private void writeJson(String json, HttpServletResponse response) {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.print(json);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != out) {
out.close();
}
}
}
}
文件上传的 目录配置了tomact的虚拟目录,在server.xml中加入:
<Context docBase="D:\upload" path="/upload" reloadable="true"/>
3.前台js以及html代码
<!-- 图片上传 -->
<div class="modal" id="imageModal" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content"><div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">上传图片</h4></div>
<form role="form" id="uploadForm" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="textInput">选择图片</label>
<input type="file" id="uploadFile" name="uploadFile" class="form-control" placeholder="输入部门简称">
</div>
<div class="form-group">
<label for="textInput">图片预览</label>
<img src="" id="lookImage"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button><button id="addImage" type="button" class="btn btn-primary">上传</button>
js代码(使用FormData对象进行ajax表单文件上传)
$("#addImage").click(function(){
var form = new FormData(document.getElementById("uploadForm"));
$.ajax({
type: "POST",
url:"upload/uploadFile.action",
data:form,
// 下面三个参数要指定,如果不指定,会报一个JQuery的错误
cache: false,
contentType: false,
processData: false,
async: false,
success: function(data) {
if(data.uploadFlag==true){
$("#lookImage").attr("src",data.fileAdress);
}else{
alert("上传出错");
}
}
});
});
4.效果展示