Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static /public/ file from Play 2 Scala controller

What is the preferred method to serve a static file from a Play Framework 2 Scala controller?

The file is bundled with my application, so it's not possible to hardcode a filesystem absolute /path/to/the/file, because its location depends on where the Play app happens to be installeld.

The file is placed in the public/ dir, but not in app/assets/, because I don't want Play to compile it.

(The reason I don't simply add a route to that file, is that one needs to login before accessing that file, otherwise it's of no use.)

Here is what I've done so far, but this breaks on my production server.

object Application ...

  def viewAdminPage = Action ... {
    ... authorization ...
    val adminPageFile = Play.getFile("/public/admin/index.html")
    Ok.sendFile(adminPageFile, inline = true)
  }

And in my routes file, I have this line:

GET /-/admin/ controllers.Application.viewAdminPage

The problem is that on my production server, this error happens:
FileNotFoundException: app1/public/admin/index.html

Is there some other method, rather than Play.getFile and OK.sendFile, to specify which file to serve? That never breaks in production?

(My app is installed in /some-dir/app1/ and I start it from /some-dir/ (without app1/) — perhaps everything would work if I instead started the app from /some-dir/app1/. But I'd like to know how one "should" do, to serve a static file from inside a controller? So that everything always works also on the production servers, regardless of from where I happen to start the application)

like image 369
KajMagnus Avatar asked Dec 26 '22 19:12

KajMagnus


1 Answers

Check Streaming HTTP responses doc

def index = Action {
  Ok.sendFile(
    content = new java.io.File("/tmp/fileToServe.pdf"),
    fileName = _ => "termsOfService.pdf"
  )
}

You can add some random string to the fileName (individual for each logged user) to avoid sharing download link between authenticated and non-authinticated users and also make advanced download stats.

like image 149
biesior Avatar answered Jan 18 '23 01:01

biesior