SpringMVC 文件的上传与下载
一、上传
1.pom依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.controller-servlet.xml文件
<!--
配置文件上传
id的值必须是multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<form action="${pageContext.request.contextPath}/hello/load" method="post" enctype="multipart/form-data">
用户:<input type="text" name="username"/><br>
文件:<input type="file" name="file"/><br>
<input type="submit" value="提交">
</form>
</body>
</html>
4.controller
单个文件:
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping("/load")//单个文件上传
public void upload(HttpSession session, @RequestParam("file") CommonsMultipartFile file) throws IOException {
ServletContext application = session.getServletContext();
String path = application.getRealPath("/upload/"+new SimpleDateFormat("yyyyMMdd").format(new Date()));
File f = new File(path);
f.mkdirs();
file.transferTo(new File(path,file.getOriginalFilename()));
}
}
多个文件:
@RequestMapping("/loads")
public void uploads(HttpSession session, @RequestParam("file") CommonsMultipartFile[] files ) throws IOException {
ServletContext application = session.getServletContext();
String path = application.getRealPath("/upload/"+new SimpleDateFormat("yyyyMMdd").format(new Date()));
File f = new File(path);
f.mkdirs();
for(CommonsMultipartFile file : files){//遍历文件存储即可
file.transferTo(new File(path,file.getOriginalFilename()));
}
}
二、下载
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
//new ResponseEntity<byte[]>()
String path = session.getServletContext().getRealPath("/upload/20200726/xzcs.txt");
File file = new File(path);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDispositionFormData("attachment","cs");
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
}
注:如果找不到FileUtils类,需要添加commom-io依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>