Skip to content

Commit 8447be9

Browse files
authored
feat: add a custom download api (#31)
it could return custom size of the file to download Co-authored-by: Rick <linuxsuren@users.noreply.github.com>
1 parent 69735c8 commit 8447be9

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/main/java/io/github/devopsws/demo/service/FileService.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import java.io.FileOutputStream;
44

5+
import org.apache.commons.lang3.StringUtils;
6+
import org.springframework.core.io.ByteArrayResource;
57
import org.springframework.core.io.Resource;
68
import org.springframework.core.io.UrlResource;
79
import org.springframework.http.HttpHeaders;
@@ -53,4 +55,26 @@ public ResponseEntity<Resource> downloadFile() {
5355
return ResponseEntity.notFound().build();
5456
}
5557
}
58+
59+
@GetMapping("/download/custom")
60+
public ResponseEntity<Resource> downloadCustomFile(@RequestParam(required = false) String filename,
61+
@RequestParam(required = false) Integer size) {
62+
if (StringUtils.isBlank(filename)) {
63+
filename = "test.log";
64+
}
65+
if (size == null || size <= 0) {
66+
size = 1024;
67+
}
68+
69+
Resource resource = new ByteArrayResource(new byte[size]);
70+
if (resource.exists() || resource.isReadable()) {
71+
return ResponseEntity.ok()
72+
.contentType(MediaType.APPLICATION_OCTET_STREAM)
73+
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(size))
74+
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
75+
.body(resource);
76+
} else {
77+
return ResponseEntity.notFound().build();
78+
}
79+
}
5680
}

0 commit comments

Comments
 (0)