Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning ZipOutputStream to browser

Tags:

java

html

http

zip

I have an ZipOutputStream that I want to return to the browser. The experience I would like is that the user clicks an anchor tag, and then a file download prompt is displayed for the ZipOutputStream that I have.

How do you get the ZipOutputStream back to the browser?

like image 611
stevebot Avatar asked Apr 01 '11 17:04

stevebot


People also ask

How do you write ZipOutputStream to a file?

write(byte[] buf, int off, int len) method writes an array of bytes to the current ZIP entry data. This method will block until all the bytes are written.

What is ZipOutputStream in Java?

public class ZipOutputStream extends DeflaterOutputStream. This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries.


1 Answers

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 I'm using a ByteArrayOutputStream wrapper and toByteArray but you could probably just write any other type of Outputstream directly to the response with a standard InputStream.read() OutputStream.write() loop.

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

like image 146
Jberg Avatar answered Sep 24 '22 07:09

Jberg