I want 开发者_StackOverflow社区to post a form which have many fields, one of them is a file, when I make like this
<form action="MediaManagementServlet" name="addMedia" method="post" enctype="multipart/form-data">
// many fileds
<label>upload file</label>
<input type="file" name="file" id="fileName"/>
it doesn't reach the servlet, but when I make like this
<form action="MediaManagementServlet" name="addMedia" method="post" >
it reach the servelet, but when I get the parameter of file it prints null ?
where's the point that is hidden for me?
It should definitely reach the servlet in both cases. You're likely not running the code you think you're running or are misinterpreting the results or have some JavaScript which takes over the submit but doesn't treat it correctly. Save, rebuild, redeploy and restart everything. The getParameter()
only returns null
for all fields in 1st case and for only the file in the 2nd case.
As to the null
parameter issue, when using multipart/form-data
encoding, the data is not been sent as a standard application/www-form-urlencoded
query string in the request body. Instead, it's been sent as multipart/form-data
block in the request body. The getParameter()
and consorts doesn't recognize this and hence they all return null
. You need to use getParts()
instead.
Collection<Part> parts = request.getParts();
// Loop through it and collect manually.
Or when you're still on old Servlet 2.5 or before, then you need to use Apache Commons FileUpload to parse it.
See also:
- How to upload files in JSP/Servlet?
精彩评论