[英]What is proper way to stream media with Spring MVC
I have a controller method that simply streams bytes for media (images, css, js, etc.) to the client. 我有一个控制器方法,该方法仅将媒体(图像,css,js等)的字节流传输到客户端。 I first tried something like this: 我首先尝试了这样的事情:
@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));
}
I originally tested this in Firefox, and it all seemed to work fine. 我最初是在Firefox中进行测试的,但似乎一切正常。 However, I then tried it in Chrome, and then found that none of the images work. 但是,然后我在Chrome中尝试了一下,然后发现所有图像均无效。 So, I then changed it to something like this: 因此,我将其更改为如下所示:
@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);
}
This gave the same results as before. 得到的结果与以前相同。 I saw in the developer tools that my response headers were coming down as expected, but still no image bytes 我在开发人员工具中看到我的响应标头按预期下降,但仍然没有图像字节
Next I tried something like this: 接下来,我尝试了这样的事情:
@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);
}
Without even setting any response headers, this works in Firefox and Chrome. 甚至没有设置任何响应头,就可以在Firefox和Chrome中使用。 Now, while I can just do it this last way since it works, this doesn't seem like the correct Spring MVC way. 现在,尽管我可以用它做的最后一种方法,但是它似乎并不是正确的Spring MVC方法。 I want to know why the first two things I tried didn't work, as they seem more correct. 我想知道为什么我尝试的前两件事没有用,因为它们似乎更正确。 Also, is there something I didn't try that would actually be the right way to do this? 另外,有没有我没有尝试过的东西实际上是正确的方法?
Your last approach is pretty much the way to go about it. 您的最后一种方法几乎是解决该问题的方法。 The only change that I can suggest is to not keep the entire content file to be streamed in memory, instead to stream out the content with buffering - IOUtils from Apache commons can do this for you. 我可以建议的唯一更改是,不要将整个内容文件保留在内存中,而要通过缓冲来流出内容-来自Apache commons的IOUtils可以为您做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.