2013-07-17 57 views
2

我想上传一个文件(一个zip文件是特定的)到Jersey支持的REST服务器。使用Jersey客户端上传文件的最佳方法是什么?

基本上有两种方法(我的意思是使用Jersey客户端,否则可以使用纯的servlet API或各种HTTP客户端)来这样做:

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()); 

为了完整起见,这里是服务器部分:

@POST 
    @Path("/import") 
    @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_OCTET_STREAM}) 
    public void uploadFile(File theFile) throws PlatformManagerException, IOException { 
     ... 
    } 

所以我想知道这两个客户端有什么区别?
要使用哪一个,为什么?
使用1)方法的缺点是,它增加了对jersey-multipart.jar的依赖(它额外增加了对mimepull.jar的依赖),所以为什么我要在我的类路径中需要这两个jar,如果纯泽西客户端方法2 )工作得很好。
也许一个普遍的问题是,是否有实现ZIP文件上传,客户端和服务器端的一个更好的办法...

+0

你找到了你的问题的答案?我处于类似的情况。 –

回答

2

方法1,您可以使用多的功能,例如,在同一上传多个文件时间或向POST添加额外的表单。

在这种情况下,你可以在服务器端签名改为:

@POST 
@Path("upload") 
@Consumes(MediaType.MULTIPART_FORM_DATA) 
public Response uploadMultipart(FormDataMultiPart multiPart) throws IOException { 
} 

我还发现,我在我的测试客户端注册MultiPartFeature ...

public FileUploadUnitTest extends JerseyTest { 
@Before 
    public void before() { 
     // to support file upload as a test client 
     client().register(MultiPartFeature.class); 
    } 
} 

和服务器

public class Application extends ResourceConfig { 
    public Application() { 
     register(MultiPartFeature.class); 
    } 
} 

感谢您的提问,它帮助我编写了我的球衣文件单元测试!

+0

很酷,单元测试很棒! :) – Svilen

相关问题