java – 如何为“虚拟文件”列表创建ZIP文件并输出到httpservletresponse

前端之家收集整理的这篇文章主要介绍了java – 如何为“虚拟文件”列表创建ZIP文件并输出到httpservletresponse前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我的目标是将多个java.io.File对象放入zip文件并打印到HttpServletResponse以供用户下载.

这些文件是由JAXB marshaller创建的.它是一个java.io.File对象,但它实际上不在文件系统上(它只在内存中),因此我无法创建FileInputStream.

我见过的所有资源都使用OutputStream来打印zip文件内容.但是,所有这些资源都使用FileInputStream(我无法使用).

谁知道我怎么能做到这一点?

最佳答案
看看@L_403_1@库,它提供了您需要的功能.

当然,“erickson”对你的问题发表评论是正确的.您将需要文件内容而不是java.io.File对象.在我的例子中,我假设你有一个方法
byte [] getTheContentFormSomewhere(int fileNummer),它返回fileNummer-th文件文件内容(在内存中). – 当然这个功能设计很差,但它仅用于说明.

它应该有点像这样:

void compress(final OutputStream out) {
  ZipOutputStream zipOutputStream = new ZipOutputStream(out);
  zipOutputStream.setLevel(ZipOutputStream.STORED);

  for(int i = 0; i < 10; i++) {
     //of course you need the file content of the i-th file
     byte[] oneFileContent = getTheContentFormSomewhere(i);
     addOneFileToZipArchive(zipOutputStream,"file"+i+"."txt",oneFileContent);
  }

  zipOutputStream.close();
}

void addOneFileToZipArchive(final ZipOutputStream zipStream,String fileName,byte[] content) {
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName);
    zipStream.putNextEntry(zipEntry);
    zipStream.write(pdfBytes);
    zipStream.closeEntry();
}

你的http控制器的Snipets:

HttpServletResponse response
...
  response.setContentType("application/zip");
  response.addHeader("Content-Disposition","attachment; filename=\"compress.zip\"");
  response.addHeader("Content-Transfer-Encoding","binary");
  ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
  compress(outputBuffer);
  response.getOutputStream().write(outputBuffer.toByteArray());
  response.getOutputStream().flush();
  outputBuffer.close();
原文链接:https://www.f2er.com/spring/432591.html

猜你在找的Spring相关文章