问题描述
我有一个后端(Spring Boot)API,它将数据块写入响应。我正在尝试从我的Angular代码中读取该内容。我的期望是从服务器接收大块数据。但是,在从服务器检索所有数据之前,get
的{{1}}方法不会返回任何内容。我已经给出了下面的代码
Spring Boot代码
httpClient
@GetMapping(value = "/stream",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<streamingresponsebody> fetchData(@RequestParam String path) {
try {
Pair<InputStream,Long> streamAndLen = CommonUtils.getTestStream();
InputStream stream = streamAndLen.getKey();
streamingresponsebody resp = outputStream -> {
CommonUtils.copy(stream,outputStream);
stream.close();
};
return ResponseEntity.ok()
.header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS,HttpHeaders.CONTENT_TYPE)
.header(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_OCTET_STREAM_VALUE)
.contentLength(streamAndLen.getValue())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resp);
} catch (Exception e) {
throw new RuntimeException("Could not get the data for the requested file",e);
}
}
==============CommonUtils==================
public static Pair<InputStream,Long> getTestStream() {
File file = new File("file_path_in_system");
try {
return new Pair<>(new FileInputStream(file),file.length());
} catch (FileNotFoundException e) {
e.printstacktrace();
throw new RuntimeException("File " + file.getAbsolutePath() + " is not found.",e);
}
}
public static void copy(InputStream stream,OutputStream outputStream) {
try {
int buffSize = 1024 * 4;
byte[] data = new byte[buffSize];
int length = -1;
while ((length = stream.read(data)) != -1) {
outputStream.write(data,length);
outputStream.flush();
}
} catch (IOException e) {
e.printstacktrace();
}
}
只是键和值POJO。
角度片段
Pair
我想在Angular应用程序中获取数据块(在每次从服务器调用let headers = new HttpHeaders().set('Accept','application/octet-stream');
this.http.get(env.streamURL + '?path=' + this.filePath,{ headers,observe: 'body',reportProgress: true,responseType: 'blob' })
.pipe(
map(res => {
console.log(res);
})
)
.subscribe(
(res: any) => {
console.log('res = ' + res);
}
);
之后),而不是等待所有数据块。有办法可以实现吗?
解决方法
如果您想从服务器获取数据块,我建议使用HTML 5 API,即SSE
您可以阅读有关它的更多信息
https://www.w3schools.com/html/html5_serversentevents.asp
此外,您还可以在下面的链接中查看该演示
https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_sse