如何在Vertx中通过GET方法读取PDF文件
Vert.x 实现GET接口返回PDF文件的方案
核心实现说明
你不需要手动处理Buffer的底层读写逻辑,Vert.x的文件系统API和HTTP响应API已经封装了相关能力,直接按下方方案实现即可。
前置依赖
- 确保项目中已经引入对应版本的
vertx-core和vertx-web依赖
完整实现代码
方案1:手动读取本地PDF文件返回(适合动态路径的PDF资源)
import io.vertx.core.AbstractVerticle; import io.vertx.core.Promise; import io.vertx.core.http.HttpHeaders; import io.vertx.ext.web.Router; public class PdfServerVerticle extends AbstractVerticle { @Override public void start(Promise<Void> startPromise) { Router router = Router.router(vertx); router.get("/api/pdf/download").handler(ctx -> { // 替换为实际的PDF文件存放路径 String pdfPath = "/local/path/your-target-file.pdf"; vertx.fileSystem().readFile(pdfPath, ar -> { if (ar.succeeded()) { // 读取完成后直接拿到封装好的Buffer,写入响应即可 ctx.response() .putHeader(HttpHeaders.CONTENT_TYPE, "application/pdf") // 需要强制触发下载而非浏览器预览时,打开下面的配置 // .putHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=custom-file-name.pdf") .end(ar.result()); } else { ctx.response().setStatusCode(404).end("PDF file not found"); } }); }); vertx.createHttpServer() .requestHandler(router) .listen(8080, ar -> { if (ar.succeeded()) { System.out.println("Server started on port 8080"); startPromise.complete(); } else { startPromise.fail(ar.cause()); } }); } }
方案2:大文件优化实现(避免一次性加载整个Buffer占用内存)
如果要返回的PDF文件体积较大,推荐用流传输替代全量Buffer读取:
router.get("/api/pdf/large-download").handler(ctx -> { String pdfPath = "/local/path/large-file.pdf"; vertx.fileSystem().open(pdfPath, openAr -> { if (openAr.succeeded()) { ctx.response() .putHeader(HttpHeaders.CONTENT_TYPE, "application/pdf"); // 直接把文件流pipe到响应,Vert.x自动处理分片传输 openAr.result().pipeTo(ctx.response()); } else { ctx.response().setStatusCode(500).end("Read pdf failed"); } }); });
方案3:静态PDF资源直接托管
如果PDF都放在固定的静态资源目录下,直接用StaticHandler即可,无需手动写读取逻辑:
import io.vertx.ext.web.handler.StaticHandler; // 把PDF文件放在resources/pdf目录下,访问 /static/pdf/xxx.pdf 即可直接获取 router.get("/static/pdf/*").handler(StaticHandler.create("pdf"));
注意事项
- 所有文件操作都使用Vert.x提供的异步API,不要用JDK原生的阻塞文件读取方法,避免阻塞事件循环
- Buffer由Vert.x自动封装和回收,不需要手动分配、释放内存
内容的提问来源于stack exchange,提问作者Utkal keshari Sahu
相关产品推荐
相关产品推荐

