且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SpringBoot SpringMVC实现文件下载

更新时间:2022-08-28 10:00:58

SpringBoot SpringMVC实现文件下载

   @RequestMapping(value = "/download", method = RequestMethod.GET)
    ResponseEntity<InputStreamResource> downloadFile(String log)
            throws IOException {
        String filePath = "/Users/alilang/logs/" + log
        FileSystemResource file = new FileSystemResource(filePath)
        HttpHeaders headers = new HttpHeaders()
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()))
        headers.add("Pragma", "no-cache")
        headers.add("Expires", "0")

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()))
    }