使用Spring MVC的ResponseEntity返回一个流 [英] Return a stream with Spring MVC's ResponseEntity
问题描述
我有一个Spring MVC方法,它返回 ResponseEntity
。根据检索到的特定数据,有时需要向用户返回数据流。其他时候它会返回除流之外的其他内容,有时还会返回重定向。我绝对希望这是一个流而不是字节数组,因为它可能很大。
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
将是一件非常好的事情。它。它还可以与我的函数的其他路径并行,我可以成功返回 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?
另外,我确实尝试返回 InputStream 在
ResponseEntity
中只是为了看看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);
但它抛出此异常:
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屋!