-1

Currently I am trying to read the contents of an uploaded file via the following code:

protected void doPost(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try {

        String urlConnection = "/DisplayInfo.jsp";
        Object htmlFile = request.getParameter("htmlFile");

        String contents = "";

        File f = (File) htmlFile;

        if(f.canRead()) {

            Scanner stdin = new Scanner(f);

            while(stdin.hasNextLine()) {
                contents += stdin.nextLine();
            }

            stdin.close();

        }

        //htmlFile = contents;

        request.setAttribute("htmlFile1", contents);

        getServletContext().getRequestDispatcher(urlConnection).forward(request, response);




    }
    finally {
        out.close();
    }

}

as defined by:

</form>

<form action ="MyServlet" method="post">

<input type="file" name="htmlFile">
<input type="submit" value="send">

</form>

and called via:

</b>

Something here: ${htmlFile1}
</body>

Essentially I am trying to read the contents of an html file and display said contents out on the website body. However, when I try to parse to the string contents I get an exception indicating the value is null.

Is there a better way to do what I am attempting?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Matthew
  • 817
  • 1
  • 13
  • 39
  • Do not use the `[java]` tag on the question as long as the problem is not demonstrable with solely a plain vanilla Java application class with a `main()` method. Do not use the `[html]` tag on the question as long as the problem is not demonstrable with solely a plain vanilla `.html` file. – BalusC Jul 13 '19 at 13:45
  • Well, its java code. Seems a strange policy to not include the java tag when it is indeed java code. – Matthew Jul 14 '19 at 16:58

1 Answers1

0
request.getParameter("htmlFile");

getParameter() will always return null when reading a POST request

You can get the request body by calling

request.getInputStream()
danielctf
  • 129
  • 2
  • 10
  • This answer is completely wrong. The statement *"getParameter() will always return null when reading a POST request"* is utterly false. The proposed solution of `request.getInputStream()` makes parsing uploaded files unnecessarily difficult. See the duplicate for the correct approach. – BalusC Jul 15 '19 at 10:13