一、方法步骤
1.在Spring-mvc.xml配置文件中添加多文件支持
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="10000000"/>
</bean>
2.必要的包
commons.fileupload.jar
commons.io.jar
3.页面
form加上属性enctype="multipart/form-data"
input加上multiple="multiple",如果不加只能选择单个文件
二、代码
1.jsp页面代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/file/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple="multiple"/>
<input type="submit" value="上传文件"/>
</form>
</body>
</html>
2.spring-mvc.xml添加
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="10000000"/>
</bean>
3.controller中
@RequestMapping("/upload")
public String upload(@RequestParam(value="file",required=false) MultipartFile[] files,
HttpServletRequest request)throws Exception{
String path = "E:/project/crm/upload";
logger.info("----------"+path);
for(MultipartFile file:files){
String fileName = file.getOriginalFilename();
File targetFile = new File(path, fileName);
file.transferTo(targetFile);
}
return "page/upload";
}
本文介绍如何在Spring MVC框架中实现多文件上传功能。主要步骤包括:在配置文件中添加多文件支持、引入必要的jar包、设置表单属性及提交方式、编写控制器处理文件保存等。

被折叠的 条评论
为什么被折叠?



