[英]Usage of enctype multipart/form-data in multi data type form
[英]Does form with enctype=“multipart/form-data” cause problems accessing a hidden field
我创建了一个隐藏的表单元素
<form name="UploadImage" enctype="multipart/form-data" method="post" action="UploadImage">
<label>
</label>
<input name="imgUploadObjId" id="imgUploadObjId" value="52" type="hidden">
//rest of the form here
</form>
我试图在servlet中获取该行的值(正如我之前所做的那样):
int objId = Integer.parseInt(request.getParameter("imgUploadObjId"));
但我明白了(第33行是上面的一行):
java.lang.NumberFormatException:null
java.lang.Integer.parseInt(Unknown Source)java.lang.Integer.parseInt(Unknown Source)web.objects.UploadImage.doPost(UploadImage.java:33)javax.servlet.http.HttpServlet.service(HttpServlet.java: 637)javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
有关enctype =“multipart / form-data”的表单有什么不同吗? 或者你能看到其他一些错误吗?
servlet默认使用application/x-www-form-urlencoded
编码解析参数。 但是,在Servlet 3.0之前,servlet中不支持multipart/form-data
编码。 getParameter()
调用都将返回null
。
在Servlet 3.0中,您应该使用HttpServletRequest#getParts()
来获取multipart/form-data
请求的所有部分,包括普通表单字段。 在Servlet 3.0之前,您应该使用Apache Commons FileUpload来解析multipart/form-data
请求。 有关这两种方法的详细示例,请参阅以下答案: 如何使用JSP / Servlet将文件上载到服务器?
请注意,如果您根本没有使用任何<input type="file">
字段,那么您可以将编码从<form>
移开。 然后默认为application/x-www-form-urlencoded
。
作为一种变通方法,您还可以在表单的action属性中将所需的隐藏参数添加为GET参数:
<form name="UploadImage" enctype="multipart/form-data" method="post" action="UploadImage?imgUploadObjId=52">
//rest of the form here
</form>
这将允许request.getParameter("imgUploadObjId")
调用工作。
确实有一些不同的东西。
request.getParameter
仅适用于<form>
元素的action
属性中指定的硬编码URL参数。 在你的情况下,它不包含任何。
所有其他参数将被编入表单本身,您必须通过直接解析HTTP请求的输入流来处理。
幸运的是,你不是第一个,并且有一些很好的开源库可以解决这个问题。
我一直在使用Apache FileUpload 。 您创建一个解析器并将请求对象传递给它,然后遍历不同的项目。 其中一个将是你隐藏的领域。
多部分编码不应影响隐藏文本字段。 这可能是别的东西。 你可以发布更多的HTML / Servlet代码吗?
不确定这是否有帮助,但是我在jsp页面中使用了多部分表单,这些表单被提交到struts servlet,这些页面有我的Struts Action类中接收的隐藏字段(包含在Struts ActionForm中),所以我不认为在这里有任何困难。
您是否尝试过将此值作为字符串接收并查看实际存在的内容?
您将检查servlet代码本身。 你收到了请求吗? 您可以调试应用程序,以便在尝试获取值并解析它时查看环境中存在哪些变量。
我只为该字段设置了id atttribute,它没有出现在List项目列表中。 当我添加name属性时,它出现了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.