java - Convenient way to parse incoming multipart/form-data parameters in a Servlet -


this question has answer here:

is there convenient way read , parse data incoming request.

e.g client initiate post request

urlconnection connection = new url(url).openconnection(); connection.setdooutput(true); connection.setrequestproperty("content-type", "multipart/form-data; boundary=" + boundary); printwriter writer = null; try {     outputstream output = connection.getoutputstream();     writer = new printwriter(new outputstreamwriter(output, charset), true); // true = autoflush, important!     // send normal param.     writer.println("--" + boundary);     writer.println("content-disposition: form-data; name=\"param\"");     writer.println("content-type: text/plain; charset=" + charset);     writer.println();     writer.println(param); 

i’m not able param using request.getparameter("paramname"). following code

bufferedreader reader = new bufferedreader(new inputstreamreader(     request.getinputstream()));   stringbuilder sb = new stringbuilder();   (string line; (line = reader.readline()) != null;) {    system.out.println(line);    } 

however displays content me

-----------------------------29772313742745 content-disposition: form-data; name="name" j.doe -----------------------------29772313742745 content-disposition: form-data; name="email" abuse@spamcop.com -----------------------------29772313742745 

what best way parse incoming request? don’t want write own parser, there ready solution.

multipart/form-data encoded requests indeed not default supported servlet api prior version 3.0. servlet api parses parameters default using application/x-www-form-urlencoded encoding. when using different encoding, request.getparameter() calls return null. when you're on servlet 3.0 (glassfish 3, tomcat 7, etc), can use httpservletrequest#getparts() instead. see this blog extended examples.

prior servlet 3.0, de facto standard parse multipart/form-data requests using apache commons fileupload. read user guide , frequently asked questions sections learn how use it. i've posted answer code example before here (it contains example targeting servlet 3.0).


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -