user3626042
user3626042

Reputation: 1

How to open pdf saved locally on windows server through hyperlink present inside a jsp page?

I have tried each and every post on stackoverflow but i am unable to open a pdf file neither in IE nor in mozilla firefox.I am new to JSP and servlets so i will be needing help with the code too.Please tell me a way to how to open pdf file saved locally on windows server through hyperlink present inside a jsp page?Write now the website is hosted using tomcat on windows server and client is that same server.

Upvotes: 0

Views: 1329

Answers (1)

Braj
Braj

Reputation: 46841

Here is code that is required to download a PDF file stored at server from client using hyperlink.

Servlet:

public class PDFDownloadServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // below line will tell the browser to show the download popup
        //response.setHeader("Content-disposition","attachment; filename=yourFileName.pdf");

        // content type that will tell the browser about the content type
        response.setContentType("application/pdf");

        OutputStream out = response.getOutputStream();

        // file is stored directly under the war folder
        FileInputStream in = new FileInputStream(new File("pdfFile.pdf"));

        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
}

web.xml:

<servlet>
    <servlet-name>pdfDownloadServlet</servlet-name>
    <servlet-class>com.x.y.z.PDFDownloadServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>pdfDownloadServlet</servlet-name>
    <url-pattern>/pdfDownload</url-pattern>
</servlet-mapping>

JSP:

<a href="<%=request.getContextPath() %>/pdfDownload">Click Here to download a PDF file</a>

Once PDF file is downloaded at the client (browser). Browser will search for appropriate software to open the PDF file if not found then it will prompt to save the file. It varies browser to browser.

Sometime Firefox shows PDF file in browser itself.

Upvotes: 1

Related Questions