Last active
December 22, 2022 13:37
-
-
Save Christian-Oette/c8497811efcb874cc8f03acebb9e04df to your computer and use it in GitHub Desktop.
Return a csv file from spring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FileResponseResource extends ByteArrayResource { | |
private final String fileName; | |
private final int fileLength; | |
public FileResponseResource(String fileName, final byte[] byteArray) { | |
super(byteArray); | |
this.fileName = Objects.requireNonNull(fileName); | |
this.fileLength = byteArray.length; | |
} | |
@Override | |
public String getFilename() { | |
return fileName; | |
} | |
@Override | |
public long contentLength() { | |
return fileLength; | |
} | |
public HttpHeaders createHeaders() { | |
HttpHeaders httpHeaders = new HttpHeaders(); | |
httpHeaders.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE); | |
ContentDisposition contentDisposition = ContentDisposition.attachment() | |
.filename(fileName) | |
.build(); | |
httpHeaders.set(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString()); | |
return httpHeaders; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RestController | |
public class ResourceDemoController { | |
@GetMapping(value = "/get-demo-resource", produces = {"text/csv"}) | |
public ResponseEntity<Resource> getResource() { | |
String output = "Header\nHello World"; | |
FileResponseResource resource = new FileResponseResource("output.csv", output.getBytes(StandardCharsets.UTF_8)); | |
return new ResponseEntity<>( | |
resource, | |
resource.createHeaders(), | |
HttpStatus.OK | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment