DownloadFile.jsp
<%
ServletOutputStream outStream = null;
try
{
String SContent = "Hello World"; // File content (Size is 11 bytes)
String SDocName = "temp.txt"; // File Name
outStream = response.getOutputStream(); // Getting ServletOutputStream
response.setContentType("application/download");
response.setHeader("Content-disposition","attachment;filename="+SDocName); // To pop dialog box
outStream.print(SContent);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
if (outStream != null)
outStream.close();
}
outStream.flush(); // Forcing buffered bytes to be written out.
%>
DownloadFiles.jsp
<%@page import="java.io.File"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.IOException"%>
<%@page import="java.util.zip.ZipOutputStream"%>
<%@page import="java.util.zip.ZipEntry"%>
<%!
void addFile( ZipOutputStream outZip, File f, String name )
{
FileInputStream in = null ;
try
{
// Add ZIP entry to output stream.
outZip.putNextEntry( new ZipEntry( name ) ) ;
in = new FileInputStream( f ) ;
// Transfer bytes from the file to the ZIP file
byte[] buf = new byte[ 4096 ] ;
int len ;
while( ( len = in.read( buf ) ) > 0 )
{
outZip.write( buf, 0, len ) ;
}
}
catch( IOException ex ) { ex.printStackTrace(); }
finally
{
// Complete the entry
try{ outZip.closeEntry() ; } catch( IOException ex ) { }
try{ in.close() ; } catch( IOException ex ) { }
}
}
void addFile( ZipOutputStream outZip, String fileContent, String name )
{
try
{
// Add ZIP entry to output stream.
outZip.putNextEntry( new ZipEntry( name ) ) ;
// Transfer bytes from the file to the ZIP file
byte[] buf = fileContent.getBytes(); ;
outZip.write( buf) ;
}
catch( IOException ex ) { ex.printStackTrace(); }
finally
{
// Complete the entry
try{ outZip.closeEntry() ; } catch( IOException ex ) { }
}
}
%>
<%
try
{
// set the content type and the filename
response.setContentType( "application/zip" ) ;
response.addHeader( "Content-Disposition", "attachment; filename=myzipfile.zip" ) ;
// get a ZipOutputStream, so we can zip our files together
ZipOutputStream outZip = new ZipOutputStream( response.getOutputStream() );
// add some files to the zip...
addFile( outZip, new File("c:\\temp.txt"), "temp.txt" ) ;
addFile( outZip, new File("c:\\temp.xls"), "temp.xls" ) ;
addFile( outZip, "FileContentString", "tems.txt");
// flush the stream, and close it
outZip.flush() ;
outZip.close() ;
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
%>