springboot 页面下载文件 网页下载文件功能 文件放resourcce下面

Dear 丶 2023-02-25 08:51 67阅读 0赞

SpringMVC(Springboot)返回文件方法

format_png

zhao1949 2018-10-25 09:47:13 format_png 1 6866 format_png 2 收藏 1

https://blog.csdn.net/Lynn_coder/article/details/79953977

*********************************************************

项目需要生成excel表格,然后返回给用户,用户需要下载这个excel表格,所以封装了一下返回文件流的方法

  1. public ResponseEntity<FileSystemResource> export(File file) {
  2. if (file == null) {
  3. return null;
  4. }
  5. HttpHeaders headers = new HttpHeaders();
  6. headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
  7. headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
  8. headers.add("Pragma", "no-cache");
  9. headers.add("Expires", "0");
  10. headers.add("Last-Modified", new Date().toString());
  11. headers.add("ETag", String.valueOf(System.currentTimeMillis()));
  12. return ResponseEntity .ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new FileSystemResource(file));
  13. }

使用方法很简单,传入file就行了,如果和springmvc结合一下的话,加上conroller,示例代码如下:

  1. @RequestMapping(value = "export_xls.html", method = RequestMethod.GET)
  2. public ResponseEntity<FileSystemResource> exportXls() {
  3. return export(new File("E:\\mydict.xls"));
  4. }

这段的意思就是返回E盘下的mydict.xls给用户

springboot 获取Resource目录下的文件

如图,获取user.png:

format_png 3

代码实现:

复制代码

  1. //文件路径,此处static前不能加/,否则解析不到
  2. try {
  3.   //此处的static前不能加/!!!
  4.   file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/images/user.png");    ...
  5. } catch (FileNotFoundException e) { e.printStackTrace(); }

复制代码

分类: 【Springboot】

发表评论

表情:
评论列表 (有 0 条评论,67人围观)

还没有评论,来说两句吧...

相关阅读