首先导入相关pom依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
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
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/10/30
Time: 18:38
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" enctype="multipart/form-data" method="post">
请选择文件:<input type="file" name="chenkang">
<input type="submit" value="ok">
</form>
</body>
</html>
代码
/**
* 文件上传
* @param req
* @param chenkang
* @return
*/
@RequestMapping("/upload")
public String upload(HttpServletRequest req, MultipartFile chenkang){
String fileName = chenkang.getOriginalFilename();
String contenType = chenkang.getContentType();
try {
FileUtils.copyInputStreamToFile(chenkang.getInputStream(),new File("E:\\chenkang"+fileName));
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/book/list";
}
可以在IDEA中添加硬盘与tomcat网络请求的映射