该文章基于《Spring+MyBatis企业应用实战》进行总结,旨在积累巩固
文件上传
文件的上传需要在页面中设置enctype为multipart/form-data,method为post,如下所示:
<form action="XXX" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit"/>
</form>
当传入了文件之后还需要再Controller中进行文件的获取以及处理:
@Controller
public class XXController{
@RequestMapping("XXX")
public XXX getFile(@RequestParam("file") MultipartFile file){
file.transferTo(new File("你想要存储的位置"));
}
}
Spring MVC中并没有提供MultipartResolver,因此需要在上下文中配置MultipartResolver:
<bean class="一般使用org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>XXX</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
所以需要引入额外的JAR包,一般使用Commons FileUpload组件
文件下载
文件的下载相对简单,会用到SpringMVC提供的ResponseEntity类型,该类型可以方便的进行定义返回的HttpHeaders和HttpStatus,文件的下载还是需要用Controller进行处理
@Controller
public class XXXController{
@RequestMapping("/download")
public ReponseEntity<byte[]> download(){
HttpHeanders headers = new HttpHeaders();
//通知浏览器以attachment方式进行文件下载
headers.setContentDispositionFormData("attachment","下载文件名");
herders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//FileUtils是Commons FileUpload的组件
return new ReponseEntity<byte[]>(FileUtils.readFileToByteArray(new File("下载文件绝对路径")),headers,Httpstatus.CREATED)
}
}