I am attempting to upload a file from my html page to my servlet side code and store it in an arraylist
heres my html:
<pre> <!DOCTYPE HTML> <html> <head> <title>file upload</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form action="url to my servlet java code" method="post" ENCTYPE="multipart/form-data"> <input type="file" value="browse..."/> <br/> <input type="submit" value="Upload File" /> </form> </body> </html> </pre> . .
. .
heres what i have in my servlet page's doGet() method
Part p1 = request.getPart("textfile.txt"); Scanner in = new Scanner(p1.getInputStream()); ArrayList<String> newList = new ArrayList<String>(); while(in.hasNextLine()){ newList.add(in.nextLine()); } Collections.shuffle(newList); so once i select the text file i want and hit upload, i get a nullpointerexception error.
help?
42 Answers
Because when the user arrives on the page, it's a GET operation, and so there's no requirement at all that any data has been provided to the page. But you're assuming in your code that getPart is not returning null. And yet, getPart is clearly defined as returning null if "... this request is of type multipart/form-data, but does not contain the requested Part." (ref).
Your form is defined as using POST, so you want to handle it in your doPost function, not your doGet function.
There are 2 major problems:
That code has got to be inside
doPost()method. Do not mix them up nor call the one from the other on. This is plain bad design (yes, I know that most tutorials show them that way, but that tells more about the tutorial itself). See also our servlets wiki page to learn how to use servlets properly.You haven't specified any name on the input element while you're expecting that the element has the name of
"textfile.txt"(which makes at its own no sense, you seem to be expecting that the filename of the uploaded file automagically becomes the input element name, how did you think that it would work if the enduser chooses a file with a different name?). You need to give the input element a name the usual way so that you can get thePartby exactly that name. E.g.<input type="file" name="upload" />with
Part part = request.getPart("upload"); // ...You only need to make sure that you've put
@MultipartConfigannotation on the servlet. See also bottom part of How to upload files to server using JSP/Servlet?