springboot 实现文件下载功能

作者: adm 分类: java 发布时间: 2021-05-22

文件存在在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));
    }

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!