4

I have a page that has this piece of code:

<form action="Servlet" enctype="multipart/form-data">
<input type="file" name="file">
<input type="text" name="text1">
<input type="text" name="text2">
</form>

When I use request.getParameter("text1"); in my Servlet it shows null. How can I make my Servlet receive the parameters?

Bolaum
  • 53
  • 1
  • 1
  • 5
  • http://www.jguru.com/faq/view.jsp?EID=1045507 – jmj Mar 12 '12 at 12:50
  • Possible duplicate of [How to upload files in JSP/Servlet?](http://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet/2424824#2424824), in other words: just by the same API as you retrieved the file. – BalusC Mar 12 '12 at 13:13

4 Answers4

6

All the request parameters are embedded into the multipart data. You'll have to extract them using something like Commons File Upload: http://commons.apache.org/fileupload/

gorjusborg
  • 656
  • 4
  • 18
2

Pleepleus is right, commons-fileupload is a good choice.
If you are working in servlet 3.0+ environment, you can also use its multipart support to easily finish the multipart-data parsing job. Simply add an @MultipartConfig on the servlet class, then you can receive the text data by calling request.getParameter(), very easy.

Tutorial - Uploading Files with Java Servlet Technology

Aboutblank
  • 697
  • 3
  • 14
  • 31
qiangbro
  • 128
  • 1
  • 9
2

Use getParts()

Francisco Paulo
  • 6,284
  • 26
  • 25
1

You need to send the parameter like this:

writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"" + urlParameterName + "\"" )
                .append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF);
writer.append(urlParameterValue).append(CRLF);
writer.flush();

And on servlet side, process the Form elements:

items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
       item = (FileItem) iter.next();
       if (item.isFormField()) {
          name = item.getFieldName(); 
          value = item.getString();

   }}
DejanR
  • 441
  • 4
  • 11