Java servlet通过重写doPost()来显示pdf文件

Java servlet通过重写doPost()来显示pdf文件,java,servlets,pdf,Java,Servlets,Pdf,我想创建一个接收pdf文件并显示它的web应用程序,但我遇到了一个http 500错误。我以为是从请求中提取字节数组并将其添加到响应输出流中。我哪里错了 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.ge

我想创建一个接收pdf文件并显示它的web应用程序,但我遇到了一个http 500错误。我以为是从请求中提取字节数组并将其添加到响应输出流中。我哪里错了

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getOutputStream().write(request.getParameter("f").getBytes());
    response.getOutputStream().flush();
    response.getOutputStream().close();
}
这是html页面

<body>
<form action="display" method="post" enctype="multipart/form-data">
PDF FILE : <input type="file" name="f">
<input type="submit" value="display">
</form>
</body>

您应该从多部分请求中获得有效部分。您可以使用Apache Commons FileUpload,也可以使用Servlets 3.0规范:

Part filePart = request.getPart("f"); // Retrieves <input type="file" name="f">
InputStream filecontent = filePart.getInputStream();
// ... read input stream
partfilepart=request.getPart(“f”);//检索
InputStream filecontent=filePart.getInputStream();
// ... 读取输入流

如果要向浏览器发送PDF文件,应在
输出流
写入流之前编写
响应.setContentType(“应用程序/PDF”)

确保只调用一次
response.getOutputStream()

OutputStream os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();
上载的文件未包含为请求参数。这就是代码中出现
NullPointerException
的原因。您必须通过请求的输入流获取pdf内容。为此,请使用第三方库或Servlet3规范


如果你想设置http头(即内容类型),你应该在通过
response.setHeader()

将任何字节写入
OutputStream
之前设置它们。是的,但是我得到了一个空指针异常……你认为会因为我没有设置内容类型而发生这种情况吗?
OutputStream os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();