vert.x - 如何将文件上传到 vertx FileSystem,以便我可以使用 routingContext.fileUploads() 读取文件
问题描述
我写了一个verticle来使用routingContext.fileUploads()从vertx文件系统中读取多部分表单数据。现在我想写一个测试用例。我正在尝试将文件上传到 vertx 文件系统,所以我可以调用我的 verticle 从文件系统中读取文件并测试我的代码。
解决方案
如果您使用的是 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()));
}
});
}
推荐阅读
- r - 当我使用 xts 包将数据框转换为时间序列数据时,数字和整数变量在 R 中被更改为字符变量
- javascript - 无法在我的 express.js 服务器中使用 Number() 函数 - RangeError
- javascript - 如何在反应中验证多步表单
- java - 从JAVA中的JSON动态读取和存储具有相同起始名称的字段
- svn - 如何在公司的SVN服务器中查找文件
- javascript - 为 websocket 引入中间件代理时反应热重载中断
- laravel - Laravel 的 updateOrCreate 中的 created_by 和 updated_by
- python - 如何解决 TypeError: sequence item 0: expected str instance, float found?
- html - 未调用 React 中的服务器端渲染
- javascript - 如何在 Gulp 中使用循环和异步/等待?