I\'m trying to upload a file and other form data using multipart/form-data client with Jersey. I\'m uploading to a REST web service also using Jersey. Here is the server c
Yves solution didn't work for me on the client side. I looked around a bit and found:
non of which would work with my current jersey 1.18 (see pom extract below). Most trouble was on the client side. I would get error messages like:
com.sun.jersey.api.client.ClientHandlerException: javax.ws.rs.WebApplicationException: java.lang.IllegalArgumentException: Missing body part entity of type 'text/plain'
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:155)
at com.sun.jersey.api.client.Client.handle(Client.java:652)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:682)
The server side worked quickly with this code (which doesn't do anything interesting with the uploaded InputStream yet - fit to your needs )
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
public Response uploadFile(
@FormDataParam("content") final InputStream uploadedInputStream,
@FormDataParam("fileName") String fileName) throws IOException {
String uploadContent=IOUtils.toString(uploadedInputStream);
return Response.ok(uploadContent).build();
}
the client side would work with this code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataMultiPart;
/**
* upload the given file
*
* inspired by
* http://neopatel.blogspot.de/2011/04/jersey-posting-multipart-data.html
*
* @param url
* @param uploadFile
* @return the result
* @throws IOException
*/
public String upload(String url, File uploadFile) throws IOException {
WebResource resource = Client.create().resource(url);
FormDataMultiPart form = new FormDataMultiPart();
form.field("fileName", uploadFile.getName());
FormDataBodyPart fdp = new FormDataBodyPart("content",
new FileInputStream(uploadFile),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
form.bodyPart(fdp);
String response = resource.type(MediaType.MULTIPART_FORM_DATA).post(String.class, form);
return response;
}
pom.xml extract:
1.18
com.sun.jersey
jersey-server
${jersey.version}
com.sun.jersey
jersey-client
${jersey.version}
com.sun.jersey.contribs
jersey-multipart
${jersey.version}