Программисты JAVA общаются здесь
Anonymous
JDK 17, версия весенней загрузки 3.2.5. Чтение файла и потоковая передача в ответ. Предоставление 0-байтовых данных
Сообщение
Anonymous » 14 янв 2025, 09:38
JDK 17, версия Spring Boot 3.2.5. Чтение файла и потоковая передача в ответ. Предоставление 0-байтовых данных. Вот детали кода: -
Код: Выделить всё
File file = new File(filePath);
//Added permission for file path
file.setExecutable(false);
file.setReadable(true);
file.setWritable(true);
// Create StreamingResponseBody
StreamingResponseBody responseBody = outputStream -> {
// Read file content
Path path = Paths.get(filePath);
byte[] data = Files.readAllBytes(path);
try (InputStream inputStream = new ByteArrayInputStream(data)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new RuntimeException("Error streaming PDF", e);
} finally {
deleteUserPrintDir(filePath, file);
data=null;
path=null;
}
};
return ResponseEntity.ok().header("Content-Disposition",
"attachment; fileName=\"" + file.getName() + "\"")
.contentType(org.springframework.http.MediaType.APPLICATION_PDF)
.body(responseBody);
Отдаю 0 Кб в ответ. Заранее спасибо, если кто-нибудь может помочь в этом.
Подробнее здесь:
https://stackoverflow.com/questions/793 ... -the-respo
1736836722
Anonymous
JDK 17, версия Spring Boot 3.2.5. Чтение файла и потоковая передача в ответ. Предоставление 0-байтовых данных. Вот детали кода: - [code]File file = new File(filePath); //Added permission for file path file.setExecutable(false); file.setReadable(true); file.setWritable(true); // Create StreamingResponseBody StreamingResponseBody responseBody = outputStream -> { // Read file content Path path = Paths.get(filePath); byte[] data = Files.readAllBytes(path); try (InputStream inputStream = new ByteArrayInputStream(data)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new RuntimeException("Error streaming PDF", e); } finally { deleteUserPrintDir(filePath, file); data=null; path=null; } }; return ResponseEntity.ok().header("Content-Disposition", "attachment; fileName=\"" + file.getName() + "\"") .contentType(org.springframework.http.MediaType.APPLICATION_PDF) .body(responseBody); [/code] Отдаю 0 Кб в ответ. Заранее спасибо, если кто-нибудь может помочь в этом. Подробнее здесь: [url]https://stackoverflow.com/questions/79354143/jdk-17-spring-boot-version-3-2-5-reading-the-file-and-streaming-into-the-respo[/url]