diff --git a/src/main/java/io/github/devopsws/demo/service/FileService.java b/src/main/java/io/github/devopsws/demo/service/FileService.java index 78040c4..66528ee 100644 --- a/src/main/java/io/github/devopsws/demo/service/FileService.java +++ b/src/main/java/io/github/devopsws/demo/service/FileService.java @@ -2,6 +2,8 @@ import java.io.FileOutputStream; +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; @@ -53,4 +55,26 @@ public ResponseEntity downloadFile() { return ResponseEntity.notFound().build(); } } + + @GetMapping("/download/custom") + public ResponseEntity downloadCustomFile(@RequestParam(required = false) String filename, + @RequestParam(required = false) Integer size) { + if (StringUtils.isBlank(filename)) { + filename = "test.log"; + } + if (size == null || size <= 0) { + size = 1024; + } + + Resource resource = new ByteArrayResource(new byte[size]); + if (resource.exists() || resource.isReadable()) { + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(size)) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"") + .body(resource); + } else { + return ResponseEntity.notFound().build(); + } + } }