首页 > 编程语言 > 详细

springboot 实现文件下载功能

时间:2020-05-07 21:47:47      阅读:1541      评论:0      收藏:0      [点我收藏+]

文件存在在data目录下

@GetMapping(value = "/file/download")
    public ResponseEntity<FileSystemResource> getFile(@RequestParam String fileName) throws FileNotFoundException {
        String path = System.getProperty("user.dir")+ "/data/";
        File file = new File(path + fileName);
        if (file.exists()) {
            return export(file);
        }
        System.out.println(file);
        return null;
    }


    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=" + file.getName());
        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));
    }

 

springboot 实现文件下载功能

原文:https://www.cnblogs.com/leavescy/p/12845482.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!