什么是使用Spring MVC流媒体的正确方法

dnc*_*253 5 java controller spring-mvc

我有一个控制器方法,简单地将媒体(图像,css,js等)的字节流传输到客户端.我首先尝试过这样的事情:

@RequestMapping(value="/path/to/media/**", method=RequestMethod.GET)
@ResponseBody
public byte[] getMedia(HttpServletRequest request) throws IOException
{
    //logic for getting path to media on server

    return Files.readAllBytes(Paths.get(serverPathToMedia));
}
Run Code Online (Sandbox Code Playgroud)

我最初在Firefox中对此进行了测试,看起来一切正常.但是,我在Chrome中尝试了它,然后发现没有任何图像有效.所以,我然后把它改成这样的东西:

@RequestMapping(value="/path/to/media/**", method=RequestMethod.GET)
public ResponseEntity<byte[]> getMedia(HttpServletRequest request) throws IOException
{
    //logic for getting path to media on server

    byte[] bytes = Files.readAllBytes(Paths.get(serverPathToMedia));
    //logic for setting some header values like Content-Type and Content-Length
    return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

这给出了与以前相同的结果.我在开发人员工具中看到我的响应标头按预期下降,但仍然没有图像字节

接下来我尝试了这样的事情:

@RequestMapping(value="/path/to/media/**", method=RequestMethod.GET)
public void getMedia(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    //logic for getting path to media on server

    byte[] bytes = Files.readAllBytes(Paths.get(serverPathToMedia));
    response.getOutputStream().write(bytes);
}
Run Code Online (Sandbox Code Playgroud)

甚至没有设置任何响应标头,这适用于Firefox和Chrome.现在,虽然我可以通过最后一种方式来实现它,但它似乎不是正确的Spring MVC方式.我想知道为什么我尝试的前两件事没有用,因为它们似乎更正确.另外,有没有我没试过的东西实际上是正确的方法呢?

Bij*_*men 5

你的最后一种方法几乎就是它的方法.我可以建议的唯一变化是不要将整个内容文件保存在内存中,而是通过缓冲来流出内容 - 来自Apache commons的IOUtils可以为您完成此操作.