返回InputStream SpringMVC

问题描述 投票:0回答:2
在这种情况下,有什么可能是一个可能的解决方案?我可以在返回InputStreamResource后以某种方式关闭CloseableHttpresponse吗?我确实需要使用

ClosableHttpClient

,该方法应返回一些

Stream public ResponseEntity<InputStreamResource> getFileAsStream(@PathVariable("uuid") String uuid) throws IOException, InterruptedException { CloseableHttpResponse response = fileService.importFileByUuid(uuid); try { HttpEntity entity = response.getEntity(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength())); responseHeaders.add(HttpHeaders.CONTENT_TYPE, entity.getContentType().getValue()); responseHeaders.add(HttpHeaders.CONTENT_DISPOSITION, response.getFirstHeader(HttpHeaders.CONTENT_DISPOSITION).getValue()); if (entity != null) { InputStream inputStream = entity.getContent(); InputStreamResource inputStreamResource = new InputStreamResource(inputStream); return ResponseEntity.ok() .headers(responseHeaders) .body(inputStreamResource); } throw new IllegalStateException(String.format( "Error during stream downloading, uuid = %s", uuid)); } finally { response.close(); } }

您始终可以创建从httpentity获得的输入流的副本,并使用副本创建响应率中返回的InputStreamResource。这样,可以在返回响应率之前安全地关闭从HTTPENTITY获得的原始输入流。 InputStream inputStream = entity.getContent(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(inputStream, outputStream); byte[] contentBytes = outputStream.toByteArray(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(contentBytes); InputStreamResource inputStreamResource = new InputStreamResource(byteArrayInputStream); 或保存使用字节[]并使用它来返回

ByteArrayResource
而不是
InputStreamResource
java spring-mvc httpclient inputstream closeablehttpresponse
2个回答
0
投票

使用Servlet API中的HTTP拖车标头的供应商来运行
.close()

侧效应。 filecontroller.java

    @GetMapping(path = "/document")
    public ResponseEntity<?> getSingleDocument(
            @RequestParam(name = "docPath") String documentPath,
            HttpServletResponse response
    ) {
        return fileService.fetchPDF(documentPath, response);
    }
FileService.java


0
投票


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.