Saturday, February 23, 2013

JSP download file



<%

 response.setContentType("application/xml"); 
 response.setHeader("Content-Disposition", "attachment;filename=myxmlfile.xml"); 

 File file = new File("myxmlfile.xml");
 FileInputStream fileIn = new FileInputStream(file);
 ServletOutputStream outstream = response.getOutputStream();
  
 byte[] outputByte = new byte[4096];
 //copy binary contect to output stream
 int byteRead;
 while( ( byteRead = fileIn.read(outputByte, 0, 4096)) != -1)
 {
  outstream.write(outputByte, 0, byteRead);
 }
 fileIn.close();
 outstream.flush();
 outstream.close();


 %>        



For binary files, use:
response.setContentType("application/x-download");
rather than
response.setContentType("application/xml");


No comments: