Тело StreamingResponseBody не выполняет немедленный возврат тела, но Rest API все еще находится в процессе загрузки
У меня есть приведенный ниже код - после выполнения приведенного ниже кода клиент получает немедленный ответ с пустым zip-файлом (без списка файлов), однако StreamingResponseBody все еще выполняется, читая файл за файлом и записывая в выходной поток - поэтому в клиенте я вижу только zip-файл без файлов. Пожалуйста, дайте мне знать, как я могу решить эту проблему.
@PostMapping(value = "/all", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<StreamingResponseBody> documentDownloadAll(@RequestBody MetadataParams metadataParams) {
try {
long start = System.currentTimeMillis();
List<File> documentList = reading list of files here ;
StreamingResponseBody responseBody = outputStream -> {try {
ZipOutputStream zos = new ZipOutputStream(outputStream);
try {
Collection<CompletableFuture<Map<String, byte[]>>> results = new ArrayList<>();
int i = 0;
for (File document : documentList) {
CompletableFuture<Map<String, byte[]>> completableFuture = fileNetService.downloadDocumentAsyn(document, i++);
if (completableFuture != null) {
results.add(completableFuture);
}
}
results.forEach(result -> {
result.join();
});
log.info("Before iteration");
for (CompletableFuture<Map<String, byte[]>> mapCompletableFuture : results) {
if (mapCompletableFuture != null && mapCompletableFuture.get() != null) {
String fileName = null;
byte[] fileContent = null;
for (Map.Entry<String, byte[]> map : mapCompletableFuture.get().entrySet()) {
fileName = map.getKey();
fileContent = map.getValue();
}
try {
log.info("File Name ---------------> {}", fileName);
zos.putNextEntry(new ZipEntry(fileName));
zos.write(fileContent, 0, fileContent.length);
zos.closeEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
}
log.info("End Zip");
} catch (Exception exp) {
e.printStackTrace();
}
} catch (Exception exp) {
e.printStackTrace();
}};
//write(outputStream, documentList);
log.info("Total time taken : {}", (System.currentTimeMillis() - start));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=generic_file_name.bin")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(responseBody);
} catch (Exception exception) {
return new ResponseEntity("Error while downloading ZIP file", HttpStatus.OK);
}
}
@Async("taskExecutorDoc")
public CompletableFuture<Map<String, byte[]>> downloadDocument(File path) {
try {
log.info("----------------------------------------------------->{}", i);
byte[] data = Files.readAllBytes(path.toAbsolutePath());
Map<String, byte[]> fileMap = new HashMap<>();
fileMap.put(i + "_" + path.getFileName(), data);
return CompletableFuture.completedFuture(fileMap);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Команда скручивания:
curl -v --trace-time -X 'POST' -o downloadal.zip 'http://localhost:8898/download/all' -H 'Content-type: application/json' --max-time 9000