May 07, 2003

Download an attachment/application using JSP.

Here is code to download an attachment/application using JSP.

<%@ page import="java.util.*,java.io.*"%>
<%
// Read the file name.
File f = new File ("c:/fop/mypdf/" + request.getParameter("file") );

//set the content type(can be excel/word/powerpoint etc..)
response.setContentType ("application/pdf");

//set the header and also the Name by which user will be prompted to save
response.setHeader ("Content-Disposition", "attachment;
filename=\"policy.pdf\"");

//get the file name
String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());

//Open an input stream to the file and post the file contents thru the
//servlet output stream to the client m/c

InputStream in = new FileInputStream(f);
ServletOutputStream outs = response.getOutputStream();

int bit = 256;
int i = 0;


try {


while ((bit) >= 0) {
bit = in.read();
outs.write(bit);
}


} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
%>