How does my servlet get parameters from a multipart / form-data form?

I have a page with 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 get my servlet to get parameters?

+3


source to share


4 answers


All query parameters are embedded in multipart data. You will need to extract them using something like Commons File Upload: http://commons.apache.org/fileupload/



+6


source


Use getParts ()



+1


source


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 complete the work of parsing multipart data. Just add @MultipartConfig

to the servlet class, then you can get the text data by invoking the request. getParameter()

, very simple.

Tutorial - Uploading Files with Java Servlet Technology

+1


source


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 the servlet side, handle 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();

   }}

      

0


source







All Articles