Re: Post method parameters and file attachment won't both show up
ffluhart@lexmark.com wrote:
I'm trying to send a POST request with some parameters and a file.
I've got (basically) the following code:
PostMethod method = new PostMethod(someURI);
// Set parameters:
method.addParameter("Foo", foo);
method.addParameter("Bar", bar);
// Add the file as a part
FilePart filePart = new FilePart(tempFile.getName(), tempFile);
filePart.setContentType("application/pdf");
Part[] parts = {filePart};
MultipartRequestEntity request = new
MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(request);
Now, when I turn on my HTTP sniffer (I'm using Ethereal) and execute
the method, I see something with a part that is my PDF file, but I
don't see my parameters, Foo and Bar, anywhere. My PDF is in a part
of the request that the sniffer calls "MIME multipart media
encapsulation, Type: multipart/form-data", inside that is
"Encapsulated multipart part".
If I change the order of the code like this:
PostMethod method = new PostMethod(someURI);
// Add the file as a part
FilePart filePart = new FilePart(tempFile.getName(), tempFile);
filePart.setContentType("application/pdf");
Part[] parts = {filePart};
MultipartRequestEntity request = new
MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(request);
// Set parameters:
method.addParameter("Foo", foo);
method.addParameter("Bar", bar);
then execute the method, I see my parameters, but no PDF portion of
the request. The parameters are in part of the request that my
sniffer calls "Line-based text data: application/x-www-form-
urlencoded".
I don't know what I need to do in order to get my parameters AND my
file to go through.
I hope this information is helpful to someone who can help me. I'm
not very experienced with making HTTP calls from within Java, and all
this multipart stuff is completely new to me.
Also, the receiver of my POST method is expecting to see something
like this:
--_NextPart_000_0002_01C3E1CC.3BB37320
Content-transfer-encoding: binary
Foo=ABC&Bar=123
--_NextPart_000_0002_01C3E1CC.3BB37320
Content-transfer-encoding: binary
Content-disposition: form-data; name="my.pdf"; filename="my.pdf"
Content-type: application/pdf; charset=ISO-8859-1
There are different ways data can be posted, as you saw:
"application/x-www-form-urlencoded" which gives you the ability to call
request.getParameter(), and "multipart/form-data" which wraps the parameters
in deeper structures.
If you use Apache Commons fileUpload,
<http://jakarta.apache.org/commons/fileupload/using.html>
(which requires Commons I/O, to which they link), it's easy. If you receive a
post of type "multipart/form-data" you use the fileUpload structures to access
your parameters; if you receive "application/x-www-form-urlencoded" then you
call request.getParameter().
-- Lew