十.文件处理
1.文件上传
1-1 POM依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
1-2.配置文件
<!--
文件上传
SpringMVC帮我们使用fileupload进行了解析
在它解析的过程中肯定会用到配置文件中bean的id
在底层代码中,对该bean的id做了限制
其id的值必须是multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
</bean>
1-3.JSP
<form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/><br/>
文件:<input type="file" name="file"/><br/>
<input type="submit" value="上传"/>
</form>
1-4.Controller
SpringMVC通过MultipartFile接口对文件上传进行了实现
其提供了一个实现类CommonsMultipartFile
想要实现文件上传,可以在方法的参数中直接使用CommonsMultipartFile作为参数
SpringMVC在读取请求的数据的时候,会自动对CommonsMultipartFile进行值的注入
由于
CommonsMultipartFile
是一个对象,对象默认不会自动添加@RequestParam
注解因此:必须在CommonsMultipartFile参数前主动添加
@RequestParam(key)
的注解如果在使用文件上传的时候没有传递文件的数据,则由于
@RequestParam(key)
的原因,会报错因为
@RequestParam
中的required
属性默认值为true,表示必须有值我们可以将其默认值改为false,设置为非必须即可
// 单文件上传
@RequestMapping("/upload")
public void upload(String username, @RequestParam(value = "file",required = false) CommonsMultipartFile file, HttpSession session) throws IOException {
System.out.println("username:"+username);
String cp = session.getServletContext().getRealPath("/upload");
if(!file.isEmpty()){
file.transferTo(new File(cp,file.getOriginalFilename()));
}
}
// 多文件上传
@RequestMapping("/uploads")
public void uploads(String username, @RequestParam(value = "file",required = false) CommonsMultipartFile[] files, HttpSession session) throws IOException {
System.out.println("username:"+username);
String cp = session.getServletContext().getRealPath("/upload");
for(CommonsMultipartFile file : files) {
if (!file.isEmpty()) {
file.transferTo(new File(cp, file.getOriginalFilename()));
}
}
}
2.文件下载
使用ResponseEntity实现
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
String cp = session.getServletContext().getRealPath("/resource/jstl.jar");
File file = new File(cp);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment","jstl.jar");
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}