【问题标题】:Java OutputStream : Download Multiple FilesJava OutputStream:下载多个文件
【发布时间】:2018-08-04 14:06:29
【问题描述】:

我正在尝试使用OutputStream 下载多个文件。我创建了一个 for 循环,遍历具有文件名的 Vector FileS 并下载它们。但只有第一个文件被下载。我的 Vector 在 0 处有 FileZero.xml 在 1 处有 FileOne.xml 并且只有 fileZero 被下载。请帮忙;这是我的代码

        for (int x = 0; x < FileS.size(); x++) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[1024];
            reportFile = rm.getClass().getResourceAsStream("/folder/" + FileS.elementAt(x));
            try {
                while ((nRead = reportFile.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        buffer.flush();
        byte[] byteArray = buffer.toByteArray();

        try {

            byte bytes[] = null;
            bytes = byteArray;
            response.setContentLength(bytes.length);
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "inline;filename=" + FileS.elementAt(x));
            OutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    } catch (Exception e) {
       e.printStackTrace();
    }
}

另外,我尝试注释掉 out.flush()out.close();但没有帮助。我尝试将 OutputStream 对象放在循环之外只是为了测试也没有帮助。

【问题讨论】:

  • 你没有得到任何异常吗?
  • 没有例外。我在调试中运行了代码,它通常会通过每个步骤

标签: java outputstream fileoutputstream


【解决方案1】:

关闭输出流(第一次迭代)然后尝试写入(第二次)当然是错误的。

但是即使你用单个文件的长度将out.close(), there is a problem: you setContent-Length`注释掉两次,但是你输出两个文件的内容,所以长度必须是单个长度的总和。

您似乎正尝试在一个请求中下载这两个文件。唯一可靠的方法是将它们打包成一个存档(如 ZIP 存档)并下载一个文件,请参见此处:How to download multiple files with one HTTP request?

或者只是一个一个下载。

【讨论】:

  • 是的,这是有道理的,但您提供的链接也提供了一个想法,而不是关于如何创建包含多个文件的 zip 文件的真正解决方案。不过谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
相关资源
最近更新 更多