-4

I have a question about some code not providing the expected response:

Intellij/Payara provides this error:

[2019-10-26T21:26:35.875+0200] [Payara 5.193] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=30 _ThreadName=http-thread-pool::http-listener-1(3)] [timeMillis: 1572117995875] [levelValue: 900] [[ StandardWrapperValve[FileUploadServlet]: Servlet.service() for servlet FileUploadServlet threw exception java.lang.NullPointerException at FileUploadServlet.doPost(FileUploadServlet.java:27)

The specific line number contains the code for parsing a string datatype to int.

public class FileUploadServlet extends HttpServlet {

    String result = "";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HttpSession file = request.getSession(true);
        int uploadcode = Integer.parseInt(request.getParameter("uploadcode"));
        int code = 1111;
        boolean checkcode = check(uploadcode, code);

        if ((checkcode && ((uploadcode != 0))){
            try {
                Part filePart = request.getPart("fileToUpload");
                InputStream fileInputStream = filePart.getInputStream();
                File fileToSave = new File("filepath" +filePart.getSubmittedFileName());
                Files.copy(fileInputStream, fileToSave.toPath(), StandardCopyOption.REPLACE_EXISTING);
                result = "File send and saved";
                file.setAttribute("Bericht", result);
            } catch (Exception ex){
                result = "File not sent, please try again.";
                file.setAttribute("Bericht", result);
            } finally{
                result = "File sent and saved";
                file.setAttribute("Bericht", result);
                getServletContext().getRequestDispatcher("/Upload.jsp").forward(request, response);
            }
        } else {
            result = "incorrect upload code.";
            file.setAttribute("Bericht", result);
            getServletContext().getRequestDispatcher("/Upload.jsp").forward(request, response);
        }
    }
    public boolean check(int a, int b) {
        return a == b;
    }
}

I expect the code to match with the input and save the file to disk. Any pointers? Thanks :)

The issue might be the form?

<form id="form1" enctype="multipart/form-data" method="post"
    action="FileUploadServlet">
    <div id="fileName"></div>
    <div id="fileSize"></div>
    <div id="fileType"></div>
    <input type="number" name="uploadcode" id="uploadcode"
        placeholder="Enter upload code" required>
    <div>
        Select the file to upload:
        <br>
        <input type="file" name="fileToUpload" id="fileToUpload"
                accept="image/*" />
        <br>
        <br>
        <ul class="actions">
            <li>
                <input type="submit" class="button alt"
                    value="Send Message" />
            </li>
        </ul>
    </div>
    <div id="progressNumber"></div>
    <div id="text"></div>
</form>

Or it could be the java script upload:

function uploadFile() {
    var fd = new FormData();
    fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open("POST", "FileUploadServlet");
    xhr.send(fd);
}

Unfortunately (26-10-2019 23:10), different error:

[2019-10-26T22:57:54.019+0200] [Payara 5.193] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=29 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1572123474019] [levelValue: 900] [[
  StandardWrapperValve[FileUploadServlet]: Servlet.service() for     servlet FileUploadServlet threw exception
java.lang.NumberFormatException: For input string: ""

After the servlet I use these to pass the variables to JSP:

<%
  HttpSession file = request.getSession(false);
  String resultaat= (String)file.getAttribute("Bericht");
%>

And:

<%out.println(resultaat);%>

Solved by setting the correct file attribute and removing the finally statement, not correct using a two-state boolean.

  • What is `FileUploadServlet.java:27` in your snippet? – Curiosa Globunznik Oct 26 '19 at 19:40
  • what is the value of `uploadcode`? – Ryuzaki L Oct 26 '19 at 19:47
  • the error message says it all: `request.getParameter("uploadcode")` is returning null – FredK Oct 26 '19 at 19:47
  • parseInt will throw a NumberFormatException rather than a NullPointerException on invalid or null input, so there's something else wrong here. [Debugging](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems?noredirect=1&lq=1) will show what that is. – Curiosa Globunznik Oct 26 '19 at 19:48
  • @David probably your code request.getParameter("uploadcode") is returning null, put a verification if this value is not null before you do the parser. You also use the Integer.valueOf(string) and this method will return a Object Wrapper of int. – Juliano Pacheco Oct 26 '19 at 19:50

1 Answers1

1

The incoming request does not contain a parameter named uploadcode at all. That means the request.getParameter() call returns null, and trying to turn that into an int via Integer.parseInt in turn produces a NullPointerException.

Therefore, you either typoed uploadcode, or there is a bug in your javascript and/or HTML.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72