导入pom依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
springmvc-servlet.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
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019-10-30
Time: 下午 06:16
To change this template use File | Settings | File Templates.
--%>
<%@ 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" value="OK">
</form>
</body>
</html>
上传文件的代码:
/**
* 文件上传
* @param req
* @param xxx
* @return
*/
@RequestMapping("/upload")
public String upload(HttpServletRequest req, MultipartFile xxx){
String fileName = xxx.getOriginalFilename();
String contentType = xxx.getContentType();
try {
FileUtils.copyInputStreamToFile(xxx.getInputStream(),new File("E:/temp/"+fileName));
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/book/list";
}
在IDEA中添加硬盘与tomcat网络请求的映射
上传成功之后访问