【问题标题】:returning a Java InputStream from the model layer in MVC从 MVC 中的模型层返回 Java InputStream
【发布时间】:2014-05-25 05:01:55
【问题描述】:

我正在创建一个 MVC Web 应用程序,用户在其中下载 100mb+ 的文件。该文件以块的形式存储在 Oracle 数据库中的多个 BLOB 中。

假设您的模型中有一个名为File 的类和一个HttpServletFileController

在 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){};
    }

FileControllerdoGet(...) 方法中,我们从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 对象在 Filefinally 块中关闭。

在不提前关闭流的情况下返回流的最佳 MVC 方式是什么?

【问题讨论】:

    标签: java servlets model-view-controller jdbc inputstream


    【解决方案1】:

    除了从服务层返回输入流之外,您可以将输出流传递给方法并让服务层处理流式传输吗?

    类似这样的:

    public void getBlobs(OutputStream stream);
    

    这样服务本身可以处理输出并在数据流式传输后正确关闭连接,这也意味着服务的使用者无需担心正确缓冲数据。

    【讨论】:

      猜你喜欢
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 2013-01-04
      相关资源
      最近更新 更多