2010-09-24 79 views
0

我想要ZIP文件的一束并通过一个servlet返回ZIP。这工作正常,如果我只有一个文件,但当我尝试添加更多,似乎他们只是追加到第一个ZipEntry,从而压缩归档文件被损坏。Corupt ZIP文件servlet对多个文件归档的响应

private void writeZipResponse(HttpServletResponse response, 
    List<File> bundle) { 
    try { 
     ByteArrayOutputStream bout=new ByteArrayOutputStream(); 
     ZipOutputStream zout = new ZipOutputStream(bout); 
     ServletOutputStream out =response.getOutputStream(); 

     for (File file : bundle) { 
      FileInputStream fi = new FileInputStream(file); 
      byte bytes[] = new byte[(int)file.length()]; 

      // Read in the bytes 
      int offset = 0; 
      int numRead = 0; 
      while (offset < bytes.length && (numRead=fi.read(bytes, offset, bytes.length-offset)) >= 0) 
{ offset += numRead; } 

      // Ensure all the bytes have been read in 
      if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } 
      fi.close(); 

      ZipEntry zipEntry = new ZipEntry(file.getName()); 
      //zipEntry.setCompressedSize(file.length()); 
      zipEntry.setSize(offset); 
      CRC32 crc = new CRC32(); 
      crc.update(bytes); 
      zipEntry.setCrc(crc.getValue()); 
      zout.putNextEntry(zipEntry); 
      zout.write(bytes, 0, offset); 
      zout.closeEntry(); 
      zout.finish(); 
      fi.close(); 
     } 

    zout.close(); 

    response.setContentType("application/zip"); 
    response.setHeader("Content-Disposition", 
    "attachment; filename=hivseqdb.zip;"); 
    out.write(bout.toByteArray()); 
    out.flush(); 
    out.close(); 

    } catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
} 

回答

1

您需要移动zout.finish();线外循环。