How can my Servlet receive parameters from a multipart/form-data form?

£可爱£侵袭症+ 提交于 2019-12-05 02:51:56

问题


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?


回答1:


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/




回答2:


Use getParts()




回答3:


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




回答4:


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();

   }}


来源:https://stackoverflow.com/questions/9667169/how-can-my-servlet-receive-parameters-from-a-multipart-form-data-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!