2017-12-11 2 views
1

나는 제 1 회 한 vertx documentation에서 여기vertx 업로드 파일 올바른 접근 방식

Router router = Router.router(vertx); 
    router.route().handler(BodyHandler.create()); 
    router.post("/api/upload").handler(routingContext -> { 
     System.out.println(routingContext.fileUploads().size()); 
     routingContext.response().end(); 
    }); 
    vertx.createHttpServer().requestHandler(req -> { 
     router.accept(req); 
    }).listen(8080, listenResult -> { 
     if (listenResult.failed()) { 
      System.out.println("Could not start HTTP server"); 
      listenResult.cause().printStackTrace(); 
     } else { 
      System.out.println("Server started"); 
     } 
    }); 
    // ========================================== 
    vertx.createHttpServer().requestHandler(req -> { 
     req.bodyHandler(buff -> { 
      System.out.println(buff.toString() + " from client"); 
      req.response().end(); 
     }); 
    }).listen(8081, listenResult -> { 
     if (listenResult.failed()) { 
      System.out.println("Could not start HTTP server"); 
      listenResult.cause().printStackTrace(); 
     } else { 
      System.out.println("Server started"); 
     } 
    }); 

2 개 서버를 만들었습니다. 우편 배달부, 두 작품 시험 할 때

제 2 회 한 https://github.com/vert-x3/vertx-examples/blob/master/web-client-examples/src/main/java/io/vertx/example/webclient/send/stream/Server.java

에서입니다.

다른 프런트 엔드 코드 (예 : https://github.com/BBB/dropzone-redux-form-example)로 테스트하면 두 번째 서버 만 작동합니다.

위의 github 예제에서 업데이트 된 내용입니다.

fetch(`http://localhost:8081/api/upload`, { 
    method: 'POST', 
    headers: { 

    }, 
    body: body, 
}) 
.then(res => { 
    console.log('response status: ', res.statusText); 
    return res.json(); 
}) 
.then(res => console.log(res)) 
.catch(err => { 
    console.log("An error occurred"); 
    console.error(err); 
}); 

사실 제 1 서버에 접근하는 것을 선호합니다.

둘 다 Postman에서 테스트되었으므로 서버는 문제가 아니므로 클라이언트 측에서 조정해야합니다.

누구든지 내가 클라이언트에 추가해야하는 것을 지적 할 수 있습니까?

감사합니다.

편집

axios.post('http://localhost:50123/api/upload', fileData) 
     .then(response => { 
      console.log('got response'); 
      console.dir(response); 
     }) 
     .catch(err => { 
      console.log("Error occurred"); 
      console.dir(err); 
     }); 

axios 작품 프론트 엔드에서 파일을 전달합니다.

이제 문제는 Vertx Web Client을 사용한 단위 테스트입니다.

fs.open("content.txt", new OpenOptions(), fileRes -> { 
    if (fileRes.succeeded()) { 
    ReadStream<Buffer> fileStream = fileRes.result(); 

    String fileLen = "1024"; 

    // Send the file to the server using POST 
    client 
     .post(8080, "myserver.mycompany.com", "/some-uri") 
     .putHeader("content-length", fileLen) 
     .sendStream(fileStream, ar -> { 
     if (ar.succeeded()) { 
      // Ok 
     } 
     }); 
    } 
}); 

위의 코드는 http://vertx.io/docs/vertx-web-client/java/#_writing_request_bodies이고 첫 번째 서버에서는 작동하지 않습니다. FileUploads이 비어 있습니다.

두 번째로 작동합니다.

Edit2가

나는 간단한 HttpClient 코드를 사용하기로 결정하고, 그것은뿐만 아니라 작동합니다. How can I make a multipart/form-data POST request using Java?

CloseableHttpClient httpClient = HttpClients.createDefault(); 
    HttpPost uploadFile = new HttpPost("http://localhost:8080/upload"); 
    MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
    builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN); 

// This attaches the file to the POST: 
     File f = new File("./test.txt"); 
    builder.addBinaryBody(
      "file", 
      new FileInputStream(f), 
      ContentType.APPLICATION_OCTET_STREAM, 
      f.getName() 
    ); 

    HttpEntity multipart = builder.build(); 
    uploadFile.setEntity(multipart); 
    CloseableHttpResponse response = httpClient.execute(uploadFile); 
    HttpEntity responseEntity = response.getEntity(); 
    System.out.println(responseEntity.toString()); 
+0

수정 사항을 사용하여 문제를 변경하는 것은 매우 혼란 스럽습니다. 결국 작동하지 않는 것은 무엇입니까? 클라이언트 코드? 테스트 코드? –

+0

예, 이해합니다. 나는 주석을 사용하려고 시도했지만 편집은 너무 길다. 현재 '루트'를 사용하여 서버를 설정하는 경우'VertX'' WebClient.sendStream'을 사용하는 것이 작동하지 않습니다. 그것은 테스트로 사용됩니다. – william

답변

0

나는 당신의 마지막 예제가 작동 할 수 표시되지 않습니다. http://localhost:8080/upload에 게시하지만 경로는 /api/upload입니다. 두 번째 예에서 포트 8081을 사용하면 단순히 경로를 무시하고 수신 한 모든 것이 파일 업로드라고 가정합니다. 그것이 두 번째 예제가 "작동하는"유일한 이유입니다.

+0

감사합니다. 나는 오타를 만들었다. 그것은/api/upload입니다. 경로와 포트는 몇 가지 예를 만들고 거기에서 복사 한 이후 지저분 해지고 있습니다. 하지만 내 질문에'WebClient.sendStream'은'routes'를 사용할 때 수신되지 않습니다. – william