作者:@stars-one

本文为作者原创,转载请注明出处:https://www.cnblogs.com/kexing/p/11899194.html


最近忙着都没时间写博客了,做了个项目,实现了下载功能,没用到上传,写这篇文章也是顺便参考学习了如何实现上传,上传和下载做一篇笔记吧

下载

主要有下面的两种方式:

  • 通过ResponseEntity实现
  • 通过写HttpServletResponse的OutputStream实现

我只测试了ResponseEntity<InputStreamResource>这种方法可行,另外一种方法请各位搜索资料。

我们在controller层中,让某个方法返回ResponseEntity,之后,用户打开这个url,就会直接开始下载文件

这里,封装了一个方法export,负责把File对象转为ResponseEntity

public ResponseEntity<FileSystemResource> export(File file) {     if (file == null) {         return null;     }     HttpHeaders headers = new HttpHeaders();     headers.add("Cache-Control", "no-cache, no-store, must-revalidate");     headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");//以时间命名文件,防止出现文件存在的情况,根据实际情况修改,我这里是返回一个xls文件     headers.add("Pragma", "no-cache");     headers.add("Expires", "0");     headers.add("Last-Modified", new Date().toString());     headers.add("ETag", String.valueOf(System.currentTimeMillis()));      return ResponseEntity             .ok()             .headers(headers)             .contentLength(file.length())             .contentType(MediaType.parseMediaType("application/octet-stream"))             .body(new FileSystemResource(file)); }

Controller

@RequestMapping("download") public ResponseEntity<FileSystemResource> downloadFile() {     return export(new FIle());//这里返回调用export的结果 }

上传

1.配置

spring boot使用上传功能,得先进行配置,spring boot配置方式有两种,一种是资源文件properties配置,另外一种方式则是yml配置

properties配置:

#