简体   繁体   English

使用Java Jersey返回一个文件

[英]Return a file using Java Jersey

I am using the Java Jersey to implement a REST service. 我正在使用Java Jersey来实现REST服务。 One thing my service should provide is a file download option. 我的服务应该提供的一件事是文件下载选项。 These files are quite big and are constructed from data from db. 这些文件非常大,并且是根据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会将其附加到输出流?

使用JERSEY使用输入和输出二进制流的答案解决了这个问题

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专家是否会看到解决方案的性能问题?

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 ByteArrayInputStream and put your data there with a byte array. 您可以使用ByteArrayInputStream并将数据放在一个字节数组中,而不是写入文件。

depends on the type of underlying database connection/driver, if you have access to the JDBC layer (eg 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. 取决于底层数据库连接/驱动程序的类型,如果您有权访问JDBC层(例如使用Hibernate),则应该可以使用JDBC Streaming API流式传输数据,然后从ResultSet中获取Streams并将它们传递给Jersey的Response生成器。 I have not done this myself though.. 我自己没有这样做..

check here: 点击这里:

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

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