Play framework set download file name
Asked Answered
O

2

8

I'm returning a file from a controller, via play.mvc.Results.ok(file). However, the file downloads as "download", without a specific file name. Is there a way I can set the name for the download (i.e. image.png)?

Thanks

Oresund answered 10/6, 2013 at 15:22 Comment(0)
W
14

In order to define a specific filename, you have to set a Content-Disposition header in the response before returning the ok(file) Result.

Here is a sample code :

public static Result myAction() {
    ...
    response().setHeader("Content-Disposition", "attachment; filename=image.png");
    return ok(file);
}
Warenne answered 10/6, 2013 at 15:34 Comment(0)
B
9

The magic for this in Scala (Play 2.4.x) is

def myAction() {
    ...
    ok(file).withHeaders("Content-Disposition" -> "attachment; filename=image.png")
}

Notice that it's plural, its a map and you can have multiple values if needed.

Of course the next thing you'll want to do is make it an actual download which is done like so:

def myAction() {
    ...
    ok(file).withHeaders(CONTENT_TYPE -> "application/x-download",  CONTENT_DISPOSITION -> "attachment; filename=image.png")
}

Notice there are CONSTANTS for most headers defined in Controller https://www.playframework.com/documentation/2.4.0/api/scala/index.html#play.api.mvc.Controller

Bunsen answered 29/6, 2015 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.