我正在尝试发布包含文件和普通文本数据的表单。 我正在使用Apache CXF。以下是代码
WebClient client= WebClient.create(ROOT_URL_FILE_SERVICE);
client.type("multipart/form-data");
InputStream is= new ByteArrayInputStream(getBytes());
List<Attachment> attachments= new ArrayList();
ContentDisposition cd = new ContentDisposition("attachment;filename=image.jpg");
Attachment att= new Attachment("File", is, cd);
Attachment pageNumber= new Attachment("DATA1", MediaType.TEXT_PLAIN, "1");
Attachment OutputType= new Attachment("DATA2", MediaType.TEXT_PLAIN, "2");
attachments.add(att);
attachments.add(pageNumber);
attachments.add(OutputType);
MultipartBody body= new MultipartBody(attachments);
Response res=client.post(body);
我无法在服务器端获取任何内容(文件,DATA1,DATA2)。
我需要在上面的代码中进行修改以使其正常工作。
答案 0 :(得分:2)
检查服务器端cxf配置如下所示。
@POST
@Path("/upload")
@Produces(MediaType.TEXT_XML)
public String upload(
@Multipart(value = "File", type = MediaType.APPLICATION_OCTET_STREAM) final InputStream fileStream,
@Multipart(value = "DATA1", type = MediaType.TEXT_PLAIN) final String fileNumber,
@Multipart(value = "DATA2", type = MediaType.TEXT_PLAIN) final String outputType) {
BufferedImage image;
try {
image = ImageIO.read(fileStream);
LOG.info("Received Image with dimensions {}x{} ", image.getWidth(), image.getHeight());
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
LOG.info("Received Multipart data1 {} ", fileNumber);
LOG.info("Received Multipart data2 {} ", outputType);
return "Recieved all data";
}
测试的客户端文件
public static void main(String[] args) throws IOException {
WebClient client = WebClient.create("http://localhost:8080/services/kp/upload");
ClientConfiguration config = WebClient.getConfig(client);
config.getInInterceptors().add(new LoggingInInterceptor());
config.getOutInterceptors().add(new LoggingOutInterceptor());
client.type("multipart/form-data");
InputStream is = FileUtils.openInputStream(new File("vCenter_del.jpg"));
List<Attachment> attachments = new ArrayList<>();
ContentDisposition cd = new ContentDisposition("attachment;filename=image.jpg");
Attachment att = new Attachment("File", is, cd);
Attachment pageNumber = new Attachment("DATA1", MediaType.TEXT_PLAIN, "1");
Attachment OutputType = new Attachment("DATA2", MediaType.TEXT_PLAIN, "2");
attachments.add(att);
attachments.add(pageNumber);
attachments.add(OutputType);
MultipartBody body = new MultipartBody(attachments);
Response res = client.post(body);
String data = res.readEntity(String.class);
System.out.println(data);
}
注意:简而言之,如果content-id不匹配,如果文件,data1或内容类型,服务器在两种情况下都可能无法接收数据,您将收到适当的错误,例如400和分别为415。