使用Spring MVC的ResponseEntity返回一个流

时间:2013-12-02 16:45:03

标签: java spring servlets spring-mvc

我有一个Spring MVC方法,它返回ResponseEntity。根据检索到的特定数据,有时需要将数据流返回给用户。其他时候它会返回除流之外的其他内容,有时还会返回重定向。我绝对希望这是一个流而不是字节数组,因为它可能很大。

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

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

return new ResponseEntity(httpHeaders, HttpStatus.OK);

不幸的是,这不允许Spring HttpHeaders数据实际填充响应中的HTTP标头。这是有道理的,因为我的代码在Spring收到OutputStream之前写入ResponseEntity

以某种方式返回一个带有ResponseEntity InputStream的{​​{1}}让Spring处理它会非常好。它还可以与我的函数的其他路径并行,我可以成功返回ResponseEntity。无论如何,我可以用Spring实现这个目标吗?


此外,我确实尝试返回InputStream中的ResponseEntity,看看Spring是否会接受它。

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

但它抛出了这个例外:

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

我可以通过直接设置HttpServletResponse上的所有内容来使我的功能正常工作,但我只想用Spring执行此操作。

1 个答案:

答案 0 :(得分:86)

Spring的InputStreamResource效果很好。您需要手动设置Content-Length,否则Spring会尝试读取流以获取Content-Length。

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

我从未发现任何建议使用此课程的网页。我只是猜到了,因为我注意到有一些使用ByteArrayResource的建议。