2

我一直在开发一个 java web 应用程序,我想添加一个下载功能。我想下载位于“C:\apache-tomcat-6.0.36\webapps\xml\XML.zip”中的 zip 文件。我已将文件转换为 InputStream,但我仍然对如何从 InputStream 获取输入流数据感到困惑?

当我单击下载按钮时,它会返回 zip 文件的 0(零)字节

这是处理下载 zipfile 的控制器:

@RequestMapping("download")
public String Download(HttpServletResponse response) {

    ZipInputStream zis = null;

    try {           

        InputStream is = new FileInputStream("C:\\apache-tomcat-6.0.36\\webapps\\xml\\XML.zip");
        zis = new ZipInputStream(is);

        response.setHeader("Content-Disposition", "inline;filename=\"" + "XML.zip" + "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType("application/zip");
        IOUtils.copy(zis.getInputStream, out);
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    } 

    return null;
}

此行导致零字节 zip 文件:

IOUtils.copy(**zis.getInputStream**, out); 
4

2 回答 2

2

假设您的代码编译:

如果您已经在获取一个 zip 文件,则无需再次通过 ZipInputStream 传递它。

像这样 http://www.avajava.com/tutorials/lessons/how-do-i-serve-up-a-pdf-from-a-servlet.html

于 2013-10-10T10:24:52.083 回答
2

如果要下载整个 ZIP 文件,则不必使用ZipInputStream... 那是用于访问ZIP 文件的内容...

而不是zis.getInputStream()使用is.getInputStream(),并删除与以下相关的代码ZipInputStream

@RequestMapping("download")
public String Download(HttpServletResponse response) {

  //ZipInputStream zis = null; no need for this

  try {           

    InputStream is = new FileInputStream("C:\\apache-tomcat-6.0.36\\webapps\\xml\\XML.zip");
    //zis = new ZipInputStream(is); //no need for this

    response.setHeader("Content-Disposition", "inline;filename=\"" + "XML.zip" + "\"");
    OutputStream out = response.getOutputStream();
    response.setContentType("application/zip");
    IOUtils.copy(is, out); //no zis here, and "is" is already an InputStream instance
    out.flush();
    out.close();
  } catch (IOException e) {
    e.printStackTrace();
  } 

  return null;
}

此外,我会修改 .close() 调用:它们几乎总是最适合finally块,以确保 everzthing 正确关闭。(即使用资源块或 try-with-resource 块。)

于 2013-10-10T10:26:35.493 回答