Return ZipOutputStream to browser

I have a ZipOutputStream that I want to return to the browser. I would like the user to click on the anchor tag, and then a file download prompt is displayed to download ZipOutputStream.

How to return ZipOutputStream to browser?

+5
source share
1 answer

It was just necessary to do the same 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 use the ByteArrayOutputStream and toByteArray wrappers, but you could simply write any other type of Outputstream directly in response using the standard InputStream.read () OutputStream.write () loop.

, , , , ByteArrayOutputStream :

+12

All Articles