-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 
1
  • Use Apache commons-fileupload for it. Commented Sep 25, 2013 at 9:20

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

yeah but i got a null pointer exception...do you think that would have happened because i dint set the content type?
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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.