java - Corupt ZIP file servlet response for multiple file archive -
i'm trying zip bundle of file's , return zip through servlet. works fine if have 1 file when try add more seems being appended first zipentry , zip archive gets corrupted.
private void writezipresponse(httpservletresponse response, list<file> bundle) { try { bytearrayoutputstream bout=new bytearrayoutputstream(); zipoutputstream zout = new zipoutputstream(bout); servletoutputstream out =response.getoutputstream(); (file file : bundle) { fileinputstream fi = new fileinputstream(file); byte bytes[] = new byte[(int)file.length()]; // read in bytes int offset = 0; int numread = 0; while (offset < bytes.length && (numread=fi.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numread; } // ensure bytes have been read in if (offset < bytes.length) { throw new ioexception("could not 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(); } }
you need move zout.finish(); line outside of loop.
Comments
Post a Comment