2

我想将一个文件(具体来说是一个 zip 文件)上传到 Jersey 支持的 REST 服务器。

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

4

1 回答 1

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

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

于 2014-03-26T17:39:52.187 回答