我在服务中有以下方法:
public interface MyService {
@POST
@Path("/upload-file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
void uploadFile(@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition contentDisposition);
}
我使用WebResourceFactory创建了这个接口的实例:
final MyService buildProxy() {
final ClientBuilder clientBuidler = ClientBuilder.newBuilder();
// register components, trust manager, etc.
final WebTarget target = clientBuilder.build().target("http://myservice.example.com");
return WebResourceFactory.newResource(
MyService.class, target. false, ImmutableMultivaluedMap.empty(),
Collections.emptyList(), new Form());
}
我想使用此代理调用我的方法,但我找不到创建FormDataContentDisposition
的便捷方法。我最好的选择是创建标题字符串,然后将其传递给new FormDataContentDisposition(String header)
?我可以在某处放松我的类型以获得更方便的构造函数吗?我可以在文件上传中使用不同的,更方便的界面吗?我主要在我的界面中包含内容配置,所以在将整个内容保存到磁盘之前,我可以拒绝一个太大的文件。
答案 0 :(得分:3)
您可以在客户端使用FormDataMultipart
和服务器参数。 FormDataMultiPart
允许您以编程方式访问所有正文部分,而不是声明性地访问。这将为您提供更多的客户端自由。请参阅下面的完整测试用例
public class ProxyMultiPartTest extends JerseyTest {
public static interface IUploadResource {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
String upload(FormDataMultiPart multipart) throws Exception;
}
@Path("upload")
public static class UploadResource implements IUploadResource {
@Override
public String upload(FormDataMultiPart multiPart) throws Exception {
FormDataBodyPart bodyPart = multiPart.getField("file");
FormDataContentDisposition fdcd = bodyPart.getFormDataContentDisposition();
System.out.println("filename: " + fdcd.getFileName());
System.out.println("size: " + fdcd.getSize());
InputStream body = bodyPart.getValueAs(InputStream.class);
StringWriter writer = new StringWriter();
ReaderWriter.writeTo(new InputStreamReader(body), writer);
return writer.toString();
}
}
@Override
public ResourceConfig configure() {
return new ResourceConfig()
.register(UploadResource.class)
.register(MultiPartFeature.class)
.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
}
@Test
public void testProxyClientUpload() throws Exception {
try (Writer writer = new BufferedWriter(new FileWriter("demo.txt"))) {
writer.write("Hello World");
}
WebTarget target = target("upload").register(MultiPartFeature.class);
IUploadResource resource = WebResourceFactory.newResource(IUploadResource.class, target);
FileDataBodyPart filePart = new FileDataBodyPart("file", new File("demo.txt"));
FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.bodyPart(filePart);
String response = resource.upload(multiPart);
assertEquals("Hello World", response);
}
}