繁体   English   中英

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

[英]What is proper way to stream media with 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));
}

我最初是在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);
}

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

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

@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);
}

甚至没有设置任何响应头,就可以在Firefox和Chrome中使用。 现在,尽管我可以用它做的最后一种方法,但是它似乎并不是正确的Spring MVC方法。 我想知道为什么我尝试的前两件事没有用,因为它们似乎更正确。 另外,有没有我没有尝试过的东西实际上是正确的方法?

您的最后一种方法几乎是解决该问题的方法。 我可以建议的唯一更改是,不要将整个内容文件保留在内存中,而要通过缓冲来流出内容-来自Apache commons的IOUtils可以为您做到这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM