From 8447be91d7c1e3e1e2e09b631e40b5c537572bfc Mon Sep 17 00:00:00 2001 From: Rick <1450685+LinuxSuRen@users.noreply.github.com> Date: Thu, 26 Dec 2024 19:40:56 +0800 Subject: [PATCH] feat: add a custom download api (#31) it could return custom size of the file to download Co-authored-by: Rick --- .../devopsws/demo/service/FileService.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) 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(); + } + } }