开发者

Problem with posting checkbox in multipart/form-data form

开发者 https://www.devze.com 2023-03-18 15:05 出处:网络
I have a simple JSP that contains c开发者_开发问答heckbox and submit button: <form action=\"MappingSubmit.jsp\" enctype=\"multipart/form-data\" method=\"POST\" name=\"fileSubmit\">

I have a simple JSP that contains c开发者_开发问答heckbox and submit button:

<form action="MappingSubmit.jsp" enctype="multipart/form-data" method="POST" name="fileSubmit">
<input type="checkbox" name="scan" value="scan">Scan immediately<br><br>
<input type="submit" value="Submit">
</form>

and a second JSP that should read the submitted data:

<body>
<%
    response.getWriter().println(request.getParameter("scan"));
%>
</body>

The problem is that getParameter always returns null. If I remove the enctype from the form, it works. Why? No way to use checkbox in a multipart/form-data form?

Thanks Udi


The default HTML form encoding is application/x-www-form-urlencoded. The getParameter() method is relying on this. Other form encodings are not supported by getParameter(). When you're using Servlet 3.0, you should be using getParts() for this instead. Or when you're using Servlet 2.5 or older and/or when you're using a multipart/form-data parser already such as Apache Commons FileUpload, then you should be using this instead to extract the parts.

If you're not using a file upload element <input type="file"> in the same form, then you don't need the enctype="multipart/form-data" at all. You could just remove it so that it defaults to application/x-www-form-urlencoded and you can use getParameter() the usual way.

See also:

  • How to upload files to server using JSP/Servlet?


You can not access request parameters from a from with enctype="multipart/form-data". You should look at O'Reilly MultipartRequest or Apache Commons FileUpload.


if you want to get submited data,file stream data must be parsed

String tmpDir = "C:/temp";
DiskFileItemFactory dfi = new DiskFileItemFactory();
dfi.setRepository(new File(tmpDir));
ServletFileUpload fileItems = new ServletFileUpload(dfi);
fileItems.setHeaderEncoding("UTF-8");
fileItems.setSizeMax(-1);
List fileItems = null;
fileItems = fileItems.parseRequest(request);
Map paramsMap = new Hashtable();
File file = null;
for(int i = 0;i < fileItems.size();i++){
    FileItem fItem = (FileItem)fileItems.get(i);
    if(fItem.isFormField()){
        //form data
        paramsMap.put(fItem.getFieldName(), fItem.getString("UTF-8"));
    }else{
        //stream
        file = new File(tmpDir, HashEngine.getSequence());
        fItem.write(file);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消