使用 Spring MVC 的 ResponseEntity 返回一个流 [英] Return a stream with Spring MVC's ResponseEntity
问题描述
我有一个返回 ResponseEntity
的 Spring MVC 方法.根据检索到的具体数据,它有时需要向用户返回数据流.其他时候它会返回一个流以外的东西,有时会返回一个重定向.我绝对希望它是一个流而不是一个字节数组,因为它可能很大.
I have a Spring MVC method which returns a ResponseEntity
. Depending on the specific data retrieved, it sometimes needs to return a stream of data to the user. Other times it will return something other than a stream, and sometimes a redirect. I most definitely want this to be a stream and not a byte array since it can be large.
目前,我使用以下代码片段返回流:
Currently, I return the stream using the following snippet of code:
HttpHeaders httpHeaders = createHttpHeaders();
IOUtils.copy(inputStream, httpServletResponse.getOutputStream());
return new ResponseEntity(httpHeaders, HttpStatus.OK);
不幸的是,这不允许 Spring HttpHeaders
数据实际填充响应中的 HTTP 标头.这是有道理的,因为我的代码在 Spring 收到 ResponseEntity
之前写入 OutputStream
.
Unfortunately, this does not allow the Spring HttpHeaders
data to actually populate the HTTP Headers in the response. This makes sense since my code writes to the OutputStream
before Spring receives the ResponseEntity
.
以某种方式返回带有 InputStream
的 ResponseEntity
并让 Spring 处理它会非常好.它还可以与我的函数的其他路径并行,在那里我可以成功返回 ResponseEntity
.无论如何,我可以使用 Spring 来完成此任务吗?
It would be very nice to somehow return a ResponseEntity
with an InputStream
an let Spring handle it. It also would parallel the other paths of my function where I can successfully return a ResponseEntity
. Is there anyway I can accomplish this with Spring?
此外,我确实尝试在 ResponseEntity
中返回 InputStream
只是为了看看 Spring 是否会接受它.
Also, I did try returning the InputStream
in the ResponseEntity
just to see if Spring would accept it.
return new ResponseEntity(inputStream, httpHeaders, HttpStatus.OK);
但是它抛出了这个异常:
But it throws this exception:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
<小时>
我可以通过直接在 HttpServletResponse
上设置所有内容来使我的函数工作,但我只想在 Spring 中执行此操作.
I can get my function to work by setting everything on the HttpServletResponse
directly, but I would like to do this only with Spring.
推荐答案
Spring 的 InputStreamResource 运行良好.您需要手动设置 Content-Length,否则 Spring 会尝试读取流以获取 Content-Length.
Spring's InputStreamResource works well. You need to set the Content-Length manually, or it appears that Spring attempts to read the stream to obtain the Content-Length.
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
httpHeaders.setContentLength(contentLengthOfStream);
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
我从未发现任何建议使用此类的网页.我只是猜测,因为我注意到有一些使用 ByteArrayResource 的建议.
I never found any web pages suggesting using this class. I only guessed it because I noticed there were a few suggestions for using ByteArrayResource.
这篇关于使用 Spring MVC 的 ResponseEntity 返回一个流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!