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?
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);
}
}