angular - 从 Angular HttpClient 使用 Spring Boot StreamingResponseBody
问题描述
我有一个 Spring Boot 应用程序,它提供 100 个压缩并通过 StreamingResponseBody 发送的图像,有没有办法从 Angular 应用程序中使用这个服务?
@GetMapping(value = "/initialize")
public ResponseEntity<StreamingResponseBody> initializeSlider(final HttpServletResponse response,
String axis,String nodeId) {
Long totalCount = imageRepository.countImageByAxisAndNodeId(axis,nodeId);
int interval = Math.round(totalCount / 50) ;
List<Integer> sequenceList = new ArrayList<>();
for(int i=0;i<totalCount;i=i+interval){
int nextSequence = i + interval;
sequenceList.add(nextSequence);
}
System.out.println(sequenceList.toString());
System.out.println(sequenceList);
response.setContentType("application/zip");
// response.setHeader("Content-Disposition", "attachment;filename=sample.zip");
StreamingResponseBody stream = out -> {
final ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
List<Image> imageList = imageRepository.findImageBySequenceIdIn(sequenceList);
try {
imageList.stream().forEach(image -> {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(image);
oos.flush();
byte [] data = bos.toByteArray();
final InputStream inputStream = new ByteArrayInputStream(data);
final ZipEntry zipEntry = new ZipEntry(image.getName());
zipOut.putNextEntry(zipEntry);
//IOUtils.copy(inputStream,zipOut);
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.closeEntry();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
});
}catch (Exception e){
e.printStackTrace();
}finally {
zipOut.flush();
zipOut.close();
}
};
System.out.println(stream);
logger.info("steaming response {} ", stream);
return new ResponseEntity(stream, HttpStatus.OK);
}
解决方案
您可以尝试使用{ responseType: 'blob' }
作为选项。
要下载文件,您可以使用文件保护程序
import { saveAs } from 'file-saver';
this.http.get(url, { responseType: 'blob' }).subscribe((resp: any) => {
FileSaver.saveAs(resp, `abc.zip`);
})
推荐阅读
- python - 如何使用 matplotlib 将 3D numpy 数组可视化为 GIF?
- dart - 如果我们在 dart 中使用 const 构造函数创建对象,那么该对象是在编译时创建的吗?
- javascript - 暗黑破坏神 2 - 改进验证符文配方的算法
- python - 使用 Post 方法的 Python requests.request 下载内容不正确的 zip 文件
- tapkey - 在 tapkey 端点上使用 $filter
- javascript - 显示当前用户在不同国家的时间
- python - 将不同大小数组的数组转换为 numpy 数组
- haskell - 将 macOS 更新到 Monterey 后无法为 Haskell 运行 QuickCheck
- java - slide.createTable() 在使用 org.apache.poi 库创建 ppt 时生成异常
- apache - 在 Apache 上进行重定向所需的最小配置是什么?