SpringBoot实现利用浏览器下载文件

SpringBoot实现利用浏览器下载文件

@RestController
@RequestMapping("file")
@Api(tags = "下载文件")
public class downloadFile { 
	@GetMapping("/downloadFile")
    public ResponseEntity<FileSystemResource> downloadFile(String path) { 
        return export(new File(path));
    }

    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));
    }
}

前端传入路径,就可以直接下载到浏览器了。

    原文作者:xff6060
    原文地址: https://blog.csdn.net/xff6060/article/details/106354738
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞