multiple file upload
emeuwese Mar 28, 2013 10:25 PMI am using JBoss AS 7.1.1. and the multipart implementation in HttpServletRequest is not working as I expected. Is the implementation of getParts() : Collection<Part> and getPart(name) : Part in HttpServletRequest correct?
getParts() returns a collect with parts. When the parts have the same name then only the last part can be found in the list. The other parts are not accessable at all. Parts have the same name when input elements in a html form have the attribute multiple="multiple". This attribute allows selection of multiple items.
getPart(name) returns only one part even though there could be multiple parts with the name. So should their not be a method getParts(name) : Collection<Part> similar to getHeader(name:String):String and getHeaders(name:String):Enumeration<String>.
Take for example the following html form.
... <form method="post" accept-charset="UTF-8" enctype="multipart/form-data" action="/upload"> <input type="file" name="images" multiple="multiple" accept="image/png" /> <input type="submit" /> </form> ...
Most browsers like Chrome 25, IE 10, Opera 12 are sending it like the following.
... Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryI21oWgJ0TlNSk3YA ... ------WebKitFormBoundaryI21oWgJ0TlNSk3YA Content-Disposition: form-data; name="images"; filename="test1.png" Content-Type: image/png ... ------WebKitFormBoundaryI21oWgJ0TlNSk3YA Content-Disposition: form-data; name="images"; filename="test2.png" Content-Type: image/png ... ------WebKitFormBoundaryI21oWgJ0TlNSk3YA Content-Disposition: form-data; name="images"; filename="test3.png" Content-Type: image/png ... ------WebKitFormBoundaryI21oWgJ0TlNSk3YA--
Which has as result that the following code only can access the image file with the name test3.png
@WebServlet(urlPatterns={"/upload"}) @MultipartConfig(location="/tmp") public class UploadServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part imagesPart = request.getPart("images"); // returns only the last part with test3.png Logger.getLogger(UploadServlet.class.getName()).log(Level.INFO, imagesPart.getHeader("Content-Disposition")); for(Part part : request.getParts()) { // getParts() returns only 1 part, that part is the part with test3.png Logger.getLogger(UploadServlet.class.getName()).log(Level.INFO, imagesPart.getHeader("Content-Disposition")); } } }