简体   繁体   English

如何从Spring Boot端点为JavaScript客户端流式传输媒体内容

[英]How to stream media content from Spring Boot endpoint for javascript client

I have a spring boot rest service with endpoints defined like this: 我有一个Spring Boot Rest服务,其端点定义如下:

@RequestMapping(value = "...", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) //and octet for videos
@ResponseBody
public ResponseEntity<byte[]> get(...) {
   //get image as byte array and return
}

And the client side in javascript (angular) : 和客户端在javascript(角):

var headers = {headers : {..., "Accept":"image/jpeg"}}
var response = $http.get(...);
obj.imageSrc = 'data:image/jpg;base64,' + response;
obj.Image = new Image();
obj.Image.src = obj.imageSrc;

What I require 我需要什么

I thought this endpoint would behave like a regular image file on a file server so that the client can just do a get on it (for reasons outside the scope of this question, it can't actually be a raw image to access with a URL). 我以为这个端点的行为就像文件服务器上的常规图像文件一样,以便客户端可以对其进行访问(出于此问题范围之外的原因,它实际上不能是通过URL访问的原始图像)。 Apparently this isn't the case - the byte array has to be converted to base64 (is there a way around this, since the array becomes much bigger), which has the effect of rotating the image. 显然不是这种情况-字节数组必须转换为base64(有办法解决,因为数组变得更大),这具有旋转图像的效果。 I wrongly thought getting an image from an API like this in javascript would be easy :( 我错误地认为从javascript这样的API获取图像会很容易:(

Secondly, doing it this way means that javascript has to download the entire array. 其次,以这种方式进行操作意味着javascript必须下载整个数组。 Is there a way I can define the endpoint to allow for a stream so that javascript can get it in chunks (I imagine both Spring and JS have utility functions that would handle this?) 有没有一种方法可以定义端点以允许流,以便javascript可以分块获取它(我想Spring和JS都有实用程序函数可以处理此问题?)

The basic underlying question 基本的基本问题

How do I implement this properly in Spring so as to be as Javascript friendly as possible? 如何在Spring中正确实现这一点,以便尽可能地友好Javascript? Bearing in mind I want to serve both images (~5MB) and videos (~100MB) 请记住,我要同时投放图片(〜5MB)和视频(〜100MB)

Thanks in advance. 提前致谢。

EDIT Perhaps I should be using FileResourceStream as the return type? 编辑也许我应该使用FileResourceStream作为返回类型? No idea if this is the "right" way. 不知道这是否是“正确”的方法。

1) Don't use a data url. 1)不要使用数据网址。 Use the direct url of your controller-method. 使用您的控制器方法的直接url。

2) Write directly to the http-response's output: 2)直接写入http-response的输出:

@RequestMapping(value = "/dyna.jpg", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public void getImage(HttpServletResponse response) {
    //write byte-array or -stream to the response using
    // response.getOutputStream() 
}

PS In case you really need the data url there is no otherway around as you do it, since they require the base64 encoding PS:如果您确实需要数据URL,那么就别无所求了,因为它们需要base64编码

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

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