1、spring-mvc配置文件
首先在springmvc的配置文件中配置署名为multipartResolver的StandardServletMultipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
2、web.xml配置文件
在前端控制器配置文件上传的限制
<!-- spring mvc前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--文件上传配置-->
<multipart-config>
<!--上传的文件的最大限制,单位byte-->
<max-file-size>10240</max-file-size>
<!--multipart/form-data请求的最大限制,单位byte-->
<max-request-size>20480</max-request-size>
</multipart-config>
</servlet>
3、jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>fileupload</title>
</head>
<body>
<h3>Springmvc文件上传</h3>
<form action="${pageContext.request.contextPath}/mvc/file" method="post" enctype="multipart/form-data">
name:<label><input type="text" name="name"/></label>
file:<label><input type="file" name="file"/></label><br>
<input type="submit" value="上传"/>
</form>
</body>
</html>
上传的文本内容为:
4、Controller获取
@Controller
@RequestMapping("/mvc")
public class MultipartController {
@RequestMapping("/file")
@ResponseBody
public void upload(String name, MultipartFile file) throws IOException{
System.out.println(name);
//文件名称
System.out.println(file.getName());
//获取文件内容
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
String len=null;
while ((len=bufferedReader.readLine()) !=null){
System.out.println(len);
}
bufferedReader.close();
}
}
控制台显示结果为: