How to include file from external local disk file system folder in JSF

一世执手 提交于 2019-11-29 17:05:27
BalusC

There are at least two major mistakes in this construct.

First of all, you can't include JSP files using <ui:include>. It can only include Facelets files. JSP files would only be treated as "plain vanilla" XML. Further, JSP is deprecated since JSF 2.0. You shouldn't ever think of using it. The <ui:include> is also the wrong tool to embed a PDF file in output. You should be using the HTML <iframe> or <object> instead.

E.g.

<iframe src="/url/to/file.pdf" width="500" height="300"></iframe>

or, better

<object data="/url/to/file.pdf" type="application/pdf" width="500" height="300">
    <a href="/url/to/file.pdf">Download file.pdf</a>
</object>

(the <a> link is meant as graceful degradation when the browser being used doesn't support inlining application/pdf content in a HTML document, i.e. when it doesn't have Adobe Reader plugin installed)

or if you happen to use PrimeFaces

<p:media value="/url/to/file.pdf" width="500" height="300" />

Secondly, JSP is the wrong tool for the job of serving a file download. JSP is like Facelets designed as a view technology with the intent to easily produce HTML output with taglibs and EL. Basically, with your JSP approach, your PDF file is cluttered with <html> and <body> tags and therefore corrupted and not recognizable as a valid PDF file. This is by the way one of the reasons why using scriptlets is a bad practice. It has namely completely confused you as to how stuff is supposed to work. Facelets does not support any form of scriptlets and hence "automatically" forces you to do things the right way. In this particular case, that is using a normal Java class for the file download job.

You should be using a servlet instead. Here's a kickoff example, assuming that Servlet 3.0 and Java 7 is available:

@WebServlet("/Saba_PhBill.pdf")
public class PdfServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File file = new File("D:\\TNWRD_Documents\\Knowladge_Base\\Financial_and_Administrative_powers.pdf");
        response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"Saba_PhBill.pdf\"");
        Files.copy(file.toPath(), response.getOutputStream());
    }

}

(you've by the way a serious typo in "Knowladge", not sure if that's further relevant to the concrete problem)

Just replace "/url/to/file.pdf" by "#{request.contextPath}/Saba_PhBill.pdf" in above HTML examples to invoke it. In <p:media> the #{request.contextPath} is unnecessary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!