我正在创建一个 MVC 网络应用程序,用户可以在其中下载一个超过 100mb 的文件。该文件以 block 的形式存储在 Oracle 数据库中的多个 BLOB 中。
假设您的模型中有一个名为 File
的类,以及一个 HttpServlet
类 FileController
。
在 File 中,我们有一个方法来获取流以从中读取文件。它的编码是这样的......
ArrayList<InputStream> blobStreams = new ArrayList<InputStream>();
try
{
//<set up and execute JDBC query here>
while (results.next())
{
blobStreams.add(results.getBinaryStream("blob"));
}
return new SequenceInputStream(Collections.enumeration(blobStreams));
}
catch (Exception e)
{
//<exception handling>
}
finally
{
try{if (results!=null)results.close(); }catch(Exception e){};
try{if (statement!=null) statement.close();}catch(Exception e){};
try{if (connection!=null) connection.close();}catch(Exception e){};
}
在 FileController
的 doGet(...)
方法中,我们从流 fileContents
中编写如下。
final int BUFFER_SIZE = 2048;
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = fileContents.read(buffer)) > 0)
{
response.getOutputStream().write(buffer, 0, length);
}
我遇到异常,“java.io.IOException: Closed Connection”大概是因为 JDBC 对象在 File< 的
。 finally
block 中关闭了
在不过早关闭流的情况下返回流的最佳 MVC 方法是什么?
最佳答案
除了从服务层返回输入流,您能否将输出流传递到方法中并让服务层处理流?
像这样:
public void getBlobs(OutputStream stream);
这样一来,服务本身就可以处理输出并在数据流式传输后正确关闭连接,这也意味着服务的使用者无需担心正确缓冲数据。
关于java - 从 MVC 中的模型层返回 Java InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23005825/