第一步:修改web.xml
为SpringMVC添加Servlet3文件上传支持:
<servlet>
<servlet-name>SpringMVCDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
<!--SpringMVC整合Servlet3文件上传-->
<multipart-config>
<!-- <location>/</location> -->
<max-file-size>5242880</max-file-size> <!--单个文件最大大小:5MB-->
<max-request-size>20971520</max-request-size> <!--所有文件最大大小:20MB-->
<file-size-threshold>0</file-size-threshold> <!-- 超过这个大小直接存硬盘,而不是内存 -->
</multipart-config>
</servlet>
第二步:修改applicationContext.xml
添加上传文件的解析器:
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
第三步:上传文件的页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加Brand</title>
</head>
<body>
<form action="brand/add" method="post" enctype="multipart/form-data">
<input type="file" name="logo321" >
<input type="submit" value="提交">
</form>
</body>
</html>
第四步:处理文件上传的Controller
@Controller
@RequestMapping("/brand")
public class BrandController {
@PostMapping("/add")
public void add(HttpServletRequest request) throws ServletException, IOException {
final Part part = request.getPart("logo321");
String header = part.getHeader("content-disposition");//获取请求头
String originalFileName = getFileName(header); //获取文件名
final String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
String filename= WeGoConst.BRAND_LOGO_PATH+UUID.randomUUID()+suffix;
try {
part.write(filename);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 根据请求头解析出文件名
* @param header 请求头
* @return 文件名
*/
public String getFileName(String header) {
String[] temp = header.split(";")[2].split("=");
//获取文件名,兼容各种浏览器的写法
String fileName = temp[1].substring(temp[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
return fileName;
}
}