使用Jersey客户端上传文件的最佳方法是什么?

时间:2013-07-17 14:24:19

标签: java file-upload jersey jax-rs multipartform-data

我想将文件(特定的zip文件)上传到Jersey支持的REST服务器。

基本上有两种方法(我的意思是使用Jersey Client,否则可以使用纯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的依赖)所以为什么我想在我的类路径中使用纯粹的Jersey客户端方法2)工作的那两个jar一样好。
也许一个普遍的问题是,是否有更好的方法来实现ZIP文件上传,包括客户端和服务器端......

1 个答案:

答案 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);
    }
}

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