1.CommonsMultipartResovler
- Spring MVC 为文件上传提供了直接的支持,这种支持是通过即插即用的 MultipartResolver 实现的。Spring 用 Jakarta Commons FileUpload 技术实现了一个MultipartResolver 实现类:CommonsMultipartResovler
- Spring MVC 上下文中默认没有装配 MultipartResovler,因此默认情况下不能处理文件的上传工作,如果想使用 Spring的文件上传功能,需现在上下文中配置 MultipartResolver
- defaultEncoding: 必须和用户 JSP 的 pageEncoding 属性一致,以便正确解析表单的内容
- 为了让 CommonsMultipartResovler 正确工作,必须先将 Jakarta Commons FileUpload 及 Jakarta Commons io的类包添加到类路径下。
<!-- 配置 MulipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean>
2.index.jsp 中写一个文件上传的表单
<body>
<form action="springmvc/testFileUpload" enctype="multipart/form-data" method="post">
File1:<input type="file" name="file" /><br>
Desc:<input type="text" name="desc" /><br>
<input type="submit" value="Submit"/>
</form>
</body>
注意:文件上传的表单要加上 enctype=”multipart/form-data
3.controller:
@RequestMapping("/testFileUpload")
public String testFileUpload(@RequestParam("desc") String desc,
@RequestParam("file") MultipartFile file,HttpSession session) throws IOException {
//文件上传的路径
String path = "d:\\Files";
File outFile = new File(path ,file.getOriginalFilename());
OutputStream out = new FileOutputStream(outFile);
InputStream in = file.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
//FileUtils.copyInputStreamToFile(in, outFile);
return "success";
}
注意:文件上传的表单要加上 enctype=”multipart/form-data
如果文件有多个,可以将参数改为 List 就好了,即 @RequestParam(“file”) List files.
4.文件下载
要实现文件下载,需要使用 ResponseEntity
@RequestMapping("/testResponseEntity")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
byte[] body = null;
ServletContext servletContext = session.getServletContext();
//获取要下载文件的输入流
InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
body = new byte[in.available()];
in.read(body);
//设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=ABC.txt");
//设置状态
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body, headers, status);
//返回 ResponseEntity<byte[]> 给页面实现下载
return responseEntity;
}