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?
source to share
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/
source to share
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.
source to share
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();
}}
source to share