java - What is the best approach to upload a file using Jersey client? -
i want upload file (a zip file specific) jersey-backed rest server.
basically there 2 approaches (i mean using jersey client, otherwise 1 can use pure servlet api or various http clients) this:
1)
webresource webresource = resource(); final file filetoupload = new file("d:/temp.zip"); final formdatamultipart multipart = new formdatamultipart(); if (filetoupload != null) { multipart.bodypart(new filedatabodypart("file", filetoupload, mediatype.valueof("application/zip"))); } final clientresponse clientresp = webresource.type(mediatype.multipart_form_data_type).post( clientresponse.class, multipart); system.out.println("response: " + clientresp.getclientresponsestatus());
2)
file filename = new file("d:/temp.zip"); inputstream fileinstream = new fileinputstream(filename); string scontentdisposition = "attachment; filename=\"" + filename.getname() + "\""; clientresponse response = resource().type(mediatype.application_octet_stream) .header("content-disposition", scontentdisposition).post(clientresponse.class, fileinstream); system.out.println("response: " + response.getclientresponsestatus());
for sake of completeness here server part:
@post @path("/import") @consumes({mediatype.multipart_form_data, mediatype.application_octet_stream}) public void uploadfile(file thefile) throws platformmanagerexception, ioexception { ... }
so wondering difference between 2 clients?
1 use , why?
downside (for me) of using 1) approach adds dependency on jersey-multipart.jar (which additionally adds dependency on mimepull.jar) why want 2 jars in classpath if pure jersey client approach 2) works fine.
, maybe 1 general question whether there better way implement zip file upload, both client , server side...
approach 1 allows use multipart features, example, uploading multiple files @ same time, or adding form post.
in case can change server side signature to:
@post @path("upload") @consumes(mediatype.multipart_form_data) public response uploadmultipart(formdatamultipart multipart) throws ioexception { }
i found had register multipartfeature in test client...
public fileuploadunittest extends jerseytest { @before public void before() { // support file upload test client client().register(multipartfeature.class); } }
and server
public class application extends resourceconfig { public application() { register(multipartfeature.class); } }
thanks question, helped me write jersey file unit test!
Comments
Post a Comment