13 January 2009

FILE DOWNLOAD (Servlets)

//1. Web application path
String applPath = getServletConfig().getServletContext().getRealPath("/")

//2. File path
String filePath = applPath + "mydir/myfile.doc";

//3. File name
String fileName = myfile.doc;

//4. input stream
FileInputStream fis = new FileInputStream( new File(filePath ) );

//5. Output stream
PrintWriter pw = response.getWriter();

//6. Read file contents byte by byte
int c=-1;
while ((c = fis.read()) != -1)
{ pw.print((char)c);}

//7. close streams
fis.close();

//8 Flush the stream (** very important)
pw.flush();

1 comment:

Anonymous said...

Superb....... Very useful. It solved a main problem for me..Thak you very much.. Sanju is really great..