Wednesday, August 22, 2007

download file in a java servlet


here's a snippet of code to download a file - existing in server file system; to be used in an action bean, servlet or whatever your implementation:

/*
* filepath: a string representing
* full system path of the existing file
*/

FileInputStream input = new FileInputStream(filepath);
String filename =
filepath.substring(
filepath.lastIndexOf(File.separator)+1);

response.setContentType("application/x-download");
response.setHeader("Content-Disposition",
"attachment; filename=" + filename

);

OutputStream output = response.getOutputStream();
int nextbyte;
while((nextbyte=input.read())!= -1)
{
output.write(nextbyte);
}
output.flush();


No comments: