簡體   English   中英

使用Spring MVC的ResponseEntity返回一個流

[英]Return a stream with Spring MVC's ResponseEntity

我有一個Spring MVC方法,它返回一個ResponseEntity 根據檢索到的特定數據, 有時需要將數據流返回給用戶。 其他時候它會返回除流之外的其他內容,有時還會返回重定向。 我絕對希望這是一個流而不是字節數組,因為它可能很大。

目前,我使用以下代碼段返回流:

HttpHeaders httpHeaders = createHttpHeaders();
IOUtils.copy(inputStream, httpServletResponse.getOutputStream());

return new ResponseEntity(httpHeaders, HttpStatus.OK);

不幸的是,這不允許Spring HttpHeaders數據實際填充響應中的HTTP Headers。 這是有道理的,因為我的代碼在Spring收到ResponseEntity之前寫入OutputStream

以某種方式返回帶有InputStreamResponseEntity並讓Spring處理它會非常好。 它還將與我的函數的其他路徑並行,我可以成功返回ResponseEntity 無論如何,我可以用Spring完成這個任務嗎?


另外,我確實嘗試在ResponseEntity返回InputStream ,看看Spring是否會接受它。

return new ResponseEntity(inputStream, httpHeaders, HttpStatus.OK);

但它拋出了這個異常:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

我可以通過直接在HttpServletResponse上設置所有內容來使我的函數工作,但我想只用Spring做這個。

Spring的InputStreamResource效果很好。 您需要手動設置Content-Length,否則Spring會嘗試讀取流以獲取Content-Length。

InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
httpHeaders.setContentLength(contentLengthOfStream);
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);

我從未發現任何建議使用此課程的網頁。 我只是猜到了,因為我注意到有一些使用ByteArrayResource的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM