java - 如何通过jsp页面中的超链接打开本地保存在Windows服务器上的pdf?

标签 java jsp pdf

我已经尝试了 stackoverflow 上的每一篇文章,但我无法在 IE 和 mozilla firefox 中打开 pdf 文件。我对 JSP 和 servlet 很陌生,所以我也需要代码方面的帮助。请告诉我如何通过 jsp 页面中的超链接打开本地保存在 Windows 服务器上的 pdf 文件?现在写该网站是使用 Windows 服务器上的 tomcat 托管的,客户端是同一服务器。

最佳答案

下面是使用超链接从客户端下载存储在服务器上的 PDF 文件所需的代码。

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>
<小时/>

在客户端(浏览器)下载 PDF 文件后。浏览器会搜索合适的软件来打开PDF文件,如果没有找到,则会提示保存文件。它因浏览器而异。

有时 Firefox 在浏览器本身中显示 PDF 文件。

关于java - 如何通过jsp页面中的超链接打开本地保存在Windows服务器上的pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23595569/

相关文章:

java - 使用 JSP 中的浏览按钮选择文件夹

java - 编写一个程序来标记无向图的连通分量

java - 如何使用 spring-ws 客户端使用不同的 keystore 调用同一个 webservice

java - Spring MVC : Not able to use use validator, 获取 "Injection of autowired dependencies failed"

java - 异常处理和日志记录: Better Practice

java - 将 jsp 页面移至 Angular 7

html - 页脚不粘在底部

c# - 附件为pdf格式

c++ - 从模板创建用于在 Qt 中打印的 PDF 文档

pdf - ImageMagick 生成带有特殊页码的 pdf