[ACCEPTED]-Returning ZipOutputStream to browser-zip

Accepted answer
Score: 16

Just had to do this exact same thing yesterday.

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(baos);

    .... populate ZipOutputStream

    String filename = "out.zip";
    // the response variable is just a standard HttpServletResponse
    response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
    response.setContentType("application/zip");

    try{            
        response.getOutputStream().write(baos.toByteArray());
        response.flushBuffer();
    }
    catch (IOException e){
        e.printStackTrace();        
    }
    finally{
        baos.close();
    }

Note 8 I'm using a ByteArrayOutputStream wrapper 7 and toByteArray but you could probably just 6 write any other type of Outputstream directly 5 to the response with a standard InputStream.read() OutputStream.write() loop.

Off 4 hand I'm actually not sure which is faster 3 if any, but I suspect my use of ByteArrayOutputStream 2 here might not be the most memory conscious 1 approach:

More Related questions