Skip to content

Instantly share code, notes, and snippets.

@cemremengu
Last active June 4, 2020 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cemremengu/5e1e913bdbb502db21441e44f810b1e8 to your computer and use it in GitHub Desktop.
Save cemremengu/5e1e913bdbb502db21441e44f810b1e8 to your computer and use it in GitHub Desktop.
// Downloading a static resource, already saved to disk
@GetMapping(value = "/")
public ResponseEntity download() throws IOException {
var file = new File("/path/to/file");
var header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName()); // you can use any name you want here
header.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Pragma", "no-cache");
header.add("Expires", "0");
return ResponseEntity.ok()
.headers(header)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
}
// Stream download a resource without saving to disk.
// For example read from database and write to csv
@GetMapping("/")
public ResponseEntity downloadFile(HttpServletResponse response) throws IOException {
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader(HttpHeaders.EXPIRES, "0");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
response.setContentType("application/octet-stream");
var formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
try (var csvAppender = this.csvWriter.append(
new OutputStreamWriter(new GZIPOutputStream(response.getOutputStream()),
StandardCharsets.UTF_8))) {
csvAppender.appendLine(new String[] {}); // header
// for each row
while (collection.hasNext()) {
var d = collection.next();
csvAppender.appendLine(d.values().stream().map(o ->
o instanceof Date ? formatter.format((Date) o) : Objects.toString(o, ""))
.toArray(String[]::new));
}
}
return ResponseEntity.ok().build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment