0

Java SE 8 comes with the Servlet Spec 3.0 so I thought it would be very easy to process a multipart POST request, but I was wrong.

I always get zero parts, although I see in the Chrome network debugger that the payload contains two images!

What am I doing wrong?

Here is my Java Code processing the POST request:

if (request.isMultipartRequest()) {
  Collection<Part> parts = request.getParts();
  log.info("number of parts: "+parts.size());
  for (Part part : parts) {
    String fileName = getFileName(part);
    log.info("fileName = "+fileName);
  }
}
...

private String getFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    System.out.println("content-disposition header= "+contentDisp);
    String[] tokens = contentDisp.split(";");
    for (String token : tokens) {
        if (token.trim().startsWith("filename")) {
            return token.substring(token.indexOf("=") + 2, token.length()-1);
        }
    }
    return "";
}

It always logs 0 parts.

I'm using Tomcat 7 and Java SE 8.

I also think it is very weird to have this getFileName() method in my own code, I expected Java 8 to do that for me...

Any hints on how to make this work is very appreciated!

basZero
  • 4,129
  • 9
  • 51
  • 89
  • You're really mixing terms - Java 8 is not directly related to the Servlet spec - Java EE (JEE) is. Either way, you seem to have found [the tutorial](http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html) - have you followed all of it? – stdunbar Mar 28 '17 at 15:28
  • @stdunbar yes you're right, Servlet 3.0 comes with Tomcat 7 running on Java 8 (in my specific case). Sorry for that. – basZero Mar 28 '17 at 15:49

1 Answers1

0

EDITED I removed my previews answer because there is a much better one: https://stackoverflow.com/a/2424824/1484621 I think this will help you.

For clarify, the Java SE 8 and Servlet Spec 3.0 are not bonded together, Sevlet 3.0 can work with java 7 if not earlier versions. The Servlet specification released by containers, and from here the error you found maybe container depended, switch to another container(Tomcat/Jetty/GlassFish) and try again. Good luck!

Community
  • 1
  • 1
Yu Jiaao
  • 4,444
  • 5
  • 44
  • 57
  • Looks rather complex for a modern Java SE 8 approach, but I'll look into it. Thanks. There must be a much better solution than this!!! – basZero Mar 28 '17 at 15:37
  • The code does not compile like this. Where do you get the static field `UPLOADEDFILENAME_ATTRIBUTE`? – basZero Mar 28 '17 at 15:43
  • Also, the referenced class `UploadFile` at the end of the code snippet does not exist in commons-fileupload 1.3 – basZero Mar 28 '17 at 15:44
  • I tested your code and inserted a log statement at `FileItem fi = (FileItem) iter.next();`, this also retrieves ZERO parts. So this commons file upload also does not work as it is described here. – basZero Mar 28 '17 at 15:54