我正在使用intellij Idea,并且已将pdf文件保存在资源文件夹中。我想在浏览器中显示该pdf文件。

public class GetDocumentation extends HttpServlet {
  private static final Logger log = Logger.getLogger(GetDocumentation.class);
@Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    InputStream pdf_path = this.getClass().getResourceAsStream(ApplicationProperties.getProperty("PDF_PATH"));

    resp.setContentType("application/pdf");
    resp.addHeader("Content-Disposition", "attachment; filename=Documentation.pdf");
    OutputStream responseOutputStream = resp.getOutputStream();

    byte[] buf = new byte[4096];
    int len = -1;

    while ((len = pdf_path.read(buf)) != -1) {
      responseOutputStream.write(buf, 0, len);
    }
    responseOutputStream.flush();
    responseOutputStream.close();
  }
}


<a href="/documentation">Documentation</a>


我正在使用Jsp servlet,并且正在调用“ / documentation”。我的文件正在渲染,但是为空。我做错什么了吗?

最佳答案

inline Content-Disposition应该用于显示文档。将"attachment"替换为"inline"

resp.addHeader("Content-Disposition", "inline; filename=Documentation.pdf");

10-08 19:14