mercoledì 29 giugno 2011

redirect jsp response to pdf file in file system

<%@ page import="java.io.*" %>
<%@ page language="java" session="false" %>
<%@ page contentType="application/pdf" %>
<%
String file = request.getParameter("file");
String filename = request.getParameter("filename");
response.setContentType("application/pdf");
response.addHeader("Content-Disposition","inline; filename=\""+filename+"\"" );
BufferedInputStream buf=null;
ServletOutputStream myOut=null;

try{

myOut = response.getOutputStream( );
File myfile = new File(file);

//set response headers


response.setContentLength( (int) myfile.length( ) );

FileInputStream input = new FileInputStream(myfile);
buf = new BufferedInputStream(input);
int readBytes = 0;

//read from the file; write to the ServletOutputStream
while((readBytes = buf.read( )) != -1)
myOut.write(readBytes);

} catch (IOException ioe){

throw new ServletException(ioe.getMessage( ));

} finally {

//close the input/output streams
if (myOut != null)
myOut.close( );
if (buf != null)
buf.close( );

}


%>Example of calling is :

pdf.jsp?file=C:\temp\a.pdf&filename=a.pdf