首先添加相关pom依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
之前的视图解析器只能处理普通的增删改查,现在文件上传需要往之前的springmvc.xml添加一段
springmvc.xml
springmvc.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大大小(字节) 1024*1024*50=50M-->
<property name="maxUploadSize" value="52428800"></property>
<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>讲解springmvc文件上传</title>
</head>
<body>
<form action="/book/upload" method="post" enctype="multipart/form-data">
请选择文件:<input type="file" name="xxx">
<input type="submit" name="ok">
</form>
</body>
</html>
实现代码
/*文件上传*/
@RequestMapping("/upload")
public String upload(HttpServletRequest req, MultipartFile xxx){
String fileName=xxx.getOriginalFilename();
String contenType=xxx.getContentType();
try {
FileUtils.copyInputStreamToFile(xxx.getInputStream(),new File("F:/T226/"+fileName));
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/book/list";
}
添加映射