使用 Java Jersey 返回文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3900611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:32:36  来源:igfitidea点击:

Return a file using Java Jersey

javajersey

提问by digy

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.

我正在使用 Java Jersey 来实现 REST 服务。我的服务应该提供的一件事是文件下载选项。这些文件相当大,是由 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();

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 ?

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

回答by Colin Hebert

So you want to get a stream from your database ?

所以你想从你的数据库中获取一个流?

I'm not sure it's even possible.

我不确定这是否可能。

But you don't have to write a temp file to send your data. Instead of writing into the file, you could use a ByteArrayInputStreamand put your data there with a byte array.

但是您不必编写临时文件来发送数据。您可以使用ByteArrayInputStream并将数据与字节数组一起放在那里,而不是写入文件。

回答by fasseg

depends on the type of underlying database connection/driver, if you have access to the JDBC layer (e.g. using Hibernate) it should be possible to stream data using the JDBC Streaming API, then take the Streams from the ResultSet and pass them into Jersey's Response Builder. I have not done this myself though..

取决于底层数据库连接/驱动程序的类型,如果您可以访问 JDBC 层(例如使用 Hibernate),则应该可以使用 JDBC Streaming API 流式传输数据,然后从 ResultSet 中获取流并将它们传递给 Jersey 的响应建设者。虽然我自己没有这样做..

check here:

在这里检查:

回答by digy

Solved the problem by using the answer from Input and Output binary streams using JERSEY?

通过使用 JERSEY 的输入和输出二进制流的答案解决了问题吗?

回答by nishantkyal

How about

怎么样

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

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

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

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

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