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

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

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


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