【问题标题】:How to open word or pdf from web inf folder in JSP如何从 JSP 中的 web inf 文件夹中打开 word 或 pdf
【发布时间】:2017-03-01 10:11:07
【问题描述】:

我有一个需求,搜索页面有一个用户指南链接。当用户点击链接时,需要从部署在JBOSS的WAR中的WEB-INF\doc文件夹中下载Word或PDF文档。

在搜索页面有如下链接 下载PDF文件 单击链接后,用户指南文档应从 WEB-INF\doc 文件夹下载并打开

谷歌搜索后发现我们需要这样使用

InputStream resourceContent = context.getResourceAsStream("/WEB-INF/doc/foo.doc");

我的应用程序使用 JSP 和 Servlet 作为控制器,在这种情况下,我需要在 doGet 方法中编写以下代码

// 获取文件的 MIME 类型 字符串 mimeType = context.getMimeType(filePath); if (mimeType == null) {
// 如果未找到 MIME 映射,则设置为二进制类型 mimeType = "应用程序/八位字节流"; } System.out.println("MIME 类型:" + mimeType);

    // modifies response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // forces download
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // obtains response's output stream
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[4096];
    int bytesRead = -1;

    while ((bytesRead = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inStream.close();
    outStream.close();    

还有我需要在 WEB.XML 中配置的内容。

我的理解是点击链接时调用Servelt doGet方法下载。

请你帮忙看看步骤是什么。

提前致谢

【问题讨论】:

    标签: jsp servlets jboss web-inf


    【解决方案1】:

    是的,实现HttpServlet.doGet()方法中的逻辑

    当我处理类似的要求时(早在 2008 年),我使用此方法设置正确的 HTTP 标头以下载 (attachment=true) 或直接显示 (attachment=false) 文档:

    public static void setDownloadHeaders(HttpServletResponse aRes,
        String aContentType, String aName, boolean anAttachment) {
      if (aRes == null) {
        throw new IllegalArgumentException(
          "HttpServletResponse can't be null.");
      }
      aRes.setContentType(aContentType);
      StringBuffer tmpCd = new StringBuffer(anAttachment ? "attachment;" : 
        "inline;");
      if (aName != null) {
        tmpCd.append(" filename=\"").append(aName).append("\";");
      }
      aRes.setHeader("Content-Disposition", tmpCd.toString());
      aRes.setHeader("Pragma", "public");
      aRes.setHeader("Cache-Control", "max-age=0");
    }
    

    您必须正确选择内容类型。在我直接显示 PDF 的情况下,它是:

    setDownloadHeaders(response, "application/pdf", getPdfFileName(), false);
    

    您不需要在web.xml 中配置任何特殊内容。一切都应该适合你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 2013-11-19
      • 2018-08-20
      • 2015-01-23
      • 1970-01-01
      • 2014-06-30
      • 2011-05-16
      相关资源
      最近更新 更多