Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play framework set download file name

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

like image 978
user1193425 Avatar asked Jun 10 '13 15:06

user1193425


2 Answers

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);
}
like image 135
mguillermin Avatar answered Oct 23 '22 18:10

mguillermin


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

like image 39
Techmag Avatar answered Oct 23 '22 18:10

Techmag