Friday, March 05, 2010

File upload using Jersey Client

This post is nothing special - I just wanted to do an http file upload using Jersey's client API. There's a lot of "noise"/outdated code out there on this topic, just wanted to show an example that worked for me:



This requires Jersey 1.1.5 and the optional jersey-multipart module (the two jars at the bottom of this section)

If you're just curious about Jersey, look at how simple the server side is for file upload using Jersey:


Beautiful!

4 comments:

Anonymous said...

I've trying to use Jersey to upload a file with REST to a server whose implementation is not known.

Documentation online talks usually about server side and not client side.

With curl, the server in question respone only whith @filename requests
but I dont found the properly call to invoke the server with jersey

curl call:
curl -v -XPUT -H "Content-type: application/wsd" -d @"tmp8276837747123904337.wsd" /regiones_styles

Adam Rabung said...

@Anonymous - this code worked against Jersey on Jetty, Jetty alone, and on some file upload form I found on the web. However, it did not work against a WebObjects instance - I needed to use HttpClient for that :(

Anonymous said...

Just a short note to say thanks for the nice, neat example.

Worked using Glassfish v3.0.1 (Jersey 1.1.5)

Ben said...

Jersey was not adding "filename" to the Content-Disposition header of the uploaded file. I was able to fix this by creating the FormDataMultiPart object using this technique instead:

FormDataMultiPart fdmp = new FormDataMultiPart();
fdmp.bodyPart(new FileDataBodyPart("file-attachemnt", new File("/Users/pavel/.bashrc")));

Thanks to Pavel Bucek for this tip.