Here's a simple way using StreamingResponseBody from your controller method:
File file = getFile();return ResponseEntity.ok() .headers(headers) .contentLength(length) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(os -> { Files.copy(file.toPath(), os); Files.delete(file.toPath()); });
The lambda is shorthand for the following:
new StreamingResponseBody() { @Override public void writeTo(OutputStream os) throws IOException { Files.copy(file.toPath(), os); Files.delete(file.toPath()); }}