How to Use ServletOutputStream – for Servlet Download zip file into response Client?

Good Day!

How to Use ServletOutputStream – for Servlet Download zip file into response Client?

Description / Answer:

  • from the tomcat.apache.org lib descriptions – Provides an output stream for sending binary data to the client.
  • is an abstract class that the servlet container implements. Subclasses of this class must implement the java.io.OutputStream.write(int) method.
  • method that are regularly used are : .write() – writing what the client request and paste to servlet response client.
  • Its use to attached the Output Stream to download on browser.

example program – Servlet Class :

ServletOutputStream servletOutputStream = null;
FileInputStream fileInputStream = null;
filename = “documentInput.Zip“;

try {
File file = new File(“C://documents/temp/tempfile.zip“);
fileInputStream = new FileInputStream(file);
servletOutputStream = response.getOutputStream();

// download using browser client – change to byte
response.setContentType(“application/zip“);
response.setContentLength((int)f.length());
response.addHeader(“Content-Disposition“,”attachment;filename=\“” + filename + “\””);
byte[] arBytes = new byte[32768];

int count;
while ((count = fileInputStream.read(arBytes)) > 0)
{
servletOutputStream.write(arBytes, 0, count);
}

}catch (IException e) {
// TODO: handle exception
} finally{
servletOutputStream.flush();
fileInputStream.close();
}