2016-07-14 3 views
0

ファイルと通常のテキストデータを含むフォームを投稿しようとしています。 私はこれにApache CXFを使用しています。コードは以下の通りです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)。

上記のコードを修正する必要があります。

答えて

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

注:コンテンツIDが一致しない場合要するにそのファイル、DATA1またはコンテンツタイプには、サーバは両方のデータを受け取るいない可能性がある場合400と415のような適切なエラーが発生します。

関連する問題