使用 Java Jersey 返回文件

2022-01-21 00:00:00 java jersey

我正在使用 Java Jersey 来实现 REST 服务.我的服务应该提供的一件事是文件下载选项.这些文件很大,是由 db 中的数据构成的.

I am using the Java Jersey to implement a REST service. One thing my service should provide is a file download option. These files are quite big and are constructed from data from db.

目前我正在从数据库中获取所有数据并将其保存到文件中并返回一个

Currently I am fetching all data from the db and saving it to a file and returning a

Response.ok().entity(new FileInputStream(file)).build();

有没有一种方法可以在不从 db 完全下载数据的情况下开始提供文件,但是由于数据来自 db,所以将其附加到输出流中?

Is there a way how I can start serving the file without fully downloading the data from db, but as the data comes from db append it to the Output stream ?

推荐答案

怎么样

File fileToSend = getFile();
return Response.ok(fileToSend, "application/zip").build();

可以设置媒体类型以匹配正在发送的文件.

The media type can be set to match the file being sent.

这看起来很简单,但更重要的是,阅读本文的 Java 专家是否发现该解决方案存在性能问题?

This looks pretty straight forward but more importantly, do java experts reading this see a performance problem with the solution?

相关文章