Recently I had a requirement to upload images. The obvious solution was to upload it through form with input type=”file” set method=”post” and enctype=”multipart/form-data” while submitting the form.
Sample HTML code:
<form action="testServlet" enctype="multipart/form-data" method="post">
Type some text:
<input type="text" name="textline">
<input type="file" name="datafile">
<input type="submit" value="Submit">
On submitting the form, we use third party software to get the uploaded file. I used commons-fileupload from apache.
Now, the thing which surprised me is, the method request.getParameter(“textline”); returned null, where request is an object of HttpServletRequest and “textline” is the name of the text box.
In Java, we generally get all the form data using request.getParameter() method. The reason it returns null is when the enctype=”multipart/form-data”, the data is transmitted as a MIME stream, which is different in format from normal POST and request.getParameter() doesn’t parse MIME streams. In case we want to use other form elements we can make use of the same third party software to get the data.