0

I have a basic verticle serving files from the data folder:

public class Server extends AbstractVerticle
{ 
  @Override
  public void start() throws Exception {
    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    router.route("/static/*").handler(StaticHandler.create("data"));
    vertx.createHttpServer().requestHandler(router).listen(8080);
  }
}

The server downloads files as .docx, but renders all images or PDFs within the browser.

How can I tell my StaticHandler to download all MIME types?

Can I somehow set the Content-Disposition: attachment header globally for the whole StaticHandler? Or have some hooks where I can set it dependent on the routing context?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Lukas Weber
  • 455
  • 6
  • 13

1 Answers1

1

You can set several handlers on a route definition. On the /static/* route, set a handler which, when the response is ready to be sent, adds an extra header:

public class Server extends AbstractVerticle
{ 
  @Override
  public void start() throws Exception {
    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    router.route("/static/*")
        .handler(rc -> {
            HttpServerResponse resp = rc.response();
            resp.headersEndHandler(v-> {
              // perhaps checks response status code before adding the header
              resp.putHeader(io.vertx.core.http.HttpHeaders.CONTENT_DISPOSITION, "attachment");
            });
            rc.next();
        })
        .handler(StaticHandler.create("data"));
    vertx.createHttpServer().requestHandler(router).listen(8080);
  }
}
Lukas Weber
  • 455
  • 6
  • 13
tsegismont
  • 8,591
  • 1
  • 17
  • 27
  • this is exactly what I need! Thanks for your support :) I made two small edits to make it work (at least on my machine), maybe you can add them to your answer. – Lukas Weber May 05 '23 at 05:02