如何向泽西客户端添加新标头以上传多部分文件

时间:2014-07-16 07:24:32

标签: rest jersey jax-rs

请在下面找到泽西客户端代码上传多部分文件:

String url = "http://localhost:7070"
Client client = Client.create();
WebResource webresource = client.resource(url);
File file = new File("C://Data//image1.jpg");
File thumbnail = new File("C://Data/image2.jpg");


InputStream isthumbnail = new FileInputStream(thumbnail);
InputStream isfile = new FileInputStream(file);

FormDataMultiPart multiPart = new FormDataMultiPart();
FormDataBodyPart bodyPart1 = new FormDataBodyPart(FormDataContentDisposition.name("Thumbnail").fileName("thumbnail").build(), isthumbnail, MediaType.APPLICATION_OCTET_STREAM_TYPE);
FormDataBodyPart bodyPart2 = new FormDataBodyPart(FormDataContentDisposition.name("File").fileName("file").build(), isfile, MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(bodyPart);
multiPart.bodyPart(bodyPart1);

//New Headers
String fileContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
String thumbnailContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";

final ClientResponse clientResp = webresource.type(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.APPLICATION_XML).post(ClientResponse.class, multiPart);
System.out.println("File Upload Success with Response"+clientResp.getStatus());

我需要将String fileContentLength和thumbnailContentLength添加为标头 内容长度。 如何添加标题作为multipart的一部分并发布请求?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

使用FormDataContentDisposition作为FormDataBodyPart(FormDataContentDisposition formDataContentDisposition, Object entity, MediaType mediaType)的参数。

final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
final String value = "Hello World";
final FormDataContentDisposition dispo = FormDataContentDisposition
        .name("file")
        .fileName("test.txt")
        .size(value.getBytes().length)
        .build();
final FormDataBodyPart bodyPart = new FormDataBodyPart(dispo, value);
formDataMultiPart.bodyPart(bodyPart);