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
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
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);
}
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
© 2022 - 2024 — McMap. All rights reserved.