-1

i want to web app that takes in a pdf file and displays it but i got a http 500 error.i thought it was get extracting the byte array from the request and adding it to the response output stream. well where was i wrong?

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();
}

here is the html page

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

here is the error that i got

java.lang.NullPointerException
    display.doPost(display.java:43)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722
Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
Alvin
  • 387
  • 4
  • 7
  • 18

3 Answers3

2

You should get a valid part from your multipart request. You can use Apache Commons FileUpload, or with Servlets 3.0 Spec:

Part filePart = request.getPart("f"); // Retrieves <input type="file" name="f">
InputStream filecontent = filePart.getInputStream();
// ... read input stream
Piotr Müller
  • 5,323
  • 5
  • 55
  • 82
0

You want to send an PDF file to the browser, you should write a response.setContentType("application/pdf") before outputStream writes the stream;

Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
  • yeah but i got a null pointer exception...do you think that would have happened because i dint set the content type? – Alvin Sep 25 '13 at 09:35
0

Make sure to call response.getOutputStream() only once:

OutputStream os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();

The uploaded file is not contained as a request parameter. That is the reason for the NullPointerException in your code. You must get the pdf content via the request's input stream. Use a third pary library or Servlet 3 spec for that purpose.

If you like to set http headers (i.e. for the content type), you should set them before writing any bytes to the OutputStream via response.setHeader().