首页 > 解决方案 > 如何将文件上传到 vertx FileSystem,以便我可以使用 routingContext.fileUploads() 读取文件

问题描述

我写了一个verticle来使用routingContext.fileUploads()从vertx文件系统中读取多部分表单数据。现在我想写一个测试用例。我正在尝试将文件上传到 vertx 文件系统,所以我可以调用我的 verticle 从文件系统中读取文件并测试我的代码。

标签: vert.xvertx-eventbus

解决方案


如果您使用的是 vertx web,则必须将 a 附加BodyHandler到路由器(不要忘记添加failureHandler):

router
        .post(UPLOAD_PATH)
        .handler(BodyHandler.create(true)
                .setHandleFileUploads(true)
                .setUploadsDirectory(uploadPath))
        .handler(this::handleUpload)
        .failureHandler(rc -> {
                LOGGER.error(String.format("Failure appears on upload request: %s", failure.get()));
        });

然后您可以通过 le 上下文访问:

private void handleUpload(RoutingContext context) {
    ...

    FileUpload file = context.fileUploads().iterator().next();

    ...
}

将文件复制到您想要的路径后,您可以WebClient在测试中创建一个并访问 vert.x 文件系统以查看文件是否存在:

@Test
public void uploadTest(TestContext context) {
  Async async = context.async();

  WebClient client = WebClient.create(vertx);
  MultipartForm form = MultipartForm.create().binaryFileUpload(...);

  client
      .post(8080, "localhost", YOUR_PATH)
      .sendMultipartForm(form, ar -> {
        if (ar.succeeded()) {
          // Ok
          FileSystem fs = vertx.fileSystem();

          fs.readDir(tempFile.getAbsolutePath(), listOfFileR -> {
            if (listOfFileR.failed()) {
              context.verify(v -> fail("read dir failed", listOfFileR.cause()));
            }
            context.verify(v -> yourAssert());
            async.countDown();
          });

        } else {
          context.verify(v -> fail("Send file failed", ar.cause()));
        }
      });
}

推荐阅读