How to set 'Content-Disposition' and 'Filename' when using FileSystemResource to force a file download file?
In addition to the accepted answer, Spring has the class ContentDisposition specific for this purpose. I believe it deals with the file name sanitization.
ContentDisposition contentDisposition = ContentDisposition.builder("inline") .filename("Filename") .build(); HttpHeaders headers = new HttpHeaders(); headers.setContentDisposition(contentDisposition);
@RequestMapping(value = "/action/{abcd}/{efgh}", method = RequestMethod.GET)@PreAuthorize("@authorizationService.authorizeMethod(#id)")public HttpEntity<byte[]> doAction(@PathVariable ObjectType obj, @PathVariable Date date, HttpServletResponse response) throws IOException { ZipFileType zipFile = service.getFile(obj1.getId(), date); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getFileName()); return new HttpEntity<byte[]>(zipFile.getByteArray(), headers);}
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET) @ResponseBody public FileSystemResource getFile(@PathVariable("file_name") String fileName,HttpServletResponse response) { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=somefile.pdf"); return new FileSystemResource(new File("file full path")); }