Skip to content

Commit

Permalink
feat: add a custom download api (#31)
Browse files Browse the repository at this point in the history
it could return custom size of the file to download

Co-authored-by: Rick <[email protected]>
  • Loading branch information
LinuxSuRen and LinuxSuRen authored Dec 26, 2024
1 parent 69735c8 commit 8447be9
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/main/java/io/github/devopsws/demo/service/FileService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -53,4 +55,26 @@ public ResponseEntity<Resource> downloadFile() {
return ResponseEntity.notFound().build();
}
}

@GetMapping("/download/custom")
public ResponseEntity<Resource> 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();
}
}
}

0 comments on commit 8447be9

Please sign in to comment.