文件上传可以使用普通的表单提交,也可以使用AJAX异步提交,如果需要使用AJAX提交则需要引入juery.form.js。
1、普通的表单提交文件上传
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- spring 监听-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring 字符集过滤 -->
<filter>
<filter-name>CharacterEncoding</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>CharacterEncoding</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>
<!-- spring mvc -->
<servlet>
<servlet-name>http</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>http</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Spring @AutoWired 依赖自动注入,不需要setter方法 -->
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<!-- Spring 扫描使用注解的包路径 -->
<context:component-scan
base-package="com.it.springweb.controller" />
<!-- Freemarker模板配置 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!--Freemarker视图解析器 -->
<bean
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="requestContextAttribute" value="request" />
<property name="contentType" value="text/html; charset=utf-8" />
</bean>
<!-- Spring JSON 格式转换依赖的Jar -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<!-- 支持上传文件 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 10M -->
<property name="maxUploadSize">
<value>52428800</value>
</property>
<property name="maxInMemorySize">
<value>10240</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
</beans>
//普通的文件上传
@Controller
public class MyController {
@Autowired
public UserService userService;
@RequestMapping("/showView")
public String showView(HttpServletRequest request) {
userService.deleteUser("1");
request.setAttribute("name", "张三");
return "showView";
}
/**
*
* 文件上传 <br>
* 〈功能详细描述〉
*
* @param request
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@RequestMapping("/importFileDatas")
public String importFileDatas(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartRequest.getFile("uploadFile");
List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
BufferedReader br = null;
try {
InputStream is = multipartFile.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
String[] datas = line.split(",");
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("userName", datas[0]);
userMap.put("password", datas[1]);
userMap.put("address", datas[2]);
userMap.put("phone", datas[3]);
userList.add(userMap);
}
} catch (Exception e) {
//
} finally {
if (br != null) {
IOUtils.closeQuietly(br);
}
}
// 保存用户数据到用户表
saveBatchUserList(userList);
return "showView";
}
private void saveBatchUserList(List<Map<String, Object>> userList) {
}
}
showView.ftl:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<#assign ctxPath=request.contextPath>
<#setting number_format="#">
<script type="text/javascript" src="${ctxPath}/staticfile/js/jquery-1.7.1.js"></script>
<script>
function upload(){
$("#uploadForm").submit();
}
</script>
</head>
<body>
姓名: ${name!''}
<form name="uploadForm" id="uploadForm" action="${ctxPath}/importFileDatas.action"
method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile">
<input type="button" onclick="upload()" value="上传">
</form>
</body>
</html>
2、使用AJAX异步提交
//通过AJAX异步请求实现文件上传
@Controller
public class MyController {
/**
*
* 文件上传 <br>
* 〈功能详细描述〉
*
* @param request
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@RequestMapping("/importFileDatas")
public void importFileDatas(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartRequest.getFile("uploadFile");
List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
BufferedReader br = null;
try {
InputStream is = multipartFile.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
String[] datas = line.split(",");
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("userName", datas[0]);
userMap.put("password", datas[1]);
userMap.put("address", datas[2]);
userMap.put("phone", datas[3]);
userList.add(userMap);
}
} catch (Exception e) {
//
} finally {
if (br != null) {
IOUtils.closeQuietly(br);
}
}
// 保存用户数据到用户表
boolean flag = saveBatchUserList(userList);
Map<String, Object> result = new HashMap<String, Object>();
result.put("count", userList.size());
result.put("flag", flag ? "success" : "failed");
JSONArray jsonArray=JSONArray.fromObject(result);
try {
response.getWriter().print(jsonArray);
} catch (IOException e) {
}
}
private boolean saveBatchUserList(List<Map<String, Object>> userList) {
return false;
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<#assign ctxPath=request.contextPath>
<#setting number_format="#">
<script type="text/javascript" src="${ctxPath}/staticfile/js/jquery-1.7.1.js"></script>
<script type="text/javascript" src="${ctxPath}/staticfile/js/jquery.form.js"></script>
<script>
function upload(){
var submitForm=$("#uploadForm")[0];
var options = {
target: submitForm,
success: function(resultMap) {
//把返回的结果转化为json对象
var result=resultMap[0];
var count=result.count;
var flag=result.flag;
alert("上传"+count+"个");
alert(flag);
},
error: function(){
alert("系统异常,暂时无法访问!");
},
type: 'post',
dataType: 'json',
iframe: true,
async:false,
clearForm: false,
resetForm: false
};
$(submitForm).ajaxSubmit(options);
}
</script>
</head>
<body>
姓名: ${name!''}
<form name="uploadForm" id="uploadForm" action="${ctxPath}/importFileDatas.action"
method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile">
<input type="button" onclick="upload()" value="上传">
</form>
</body>
</html>