从 Play 2 Scala 控制器提供静态/public/文件 [英] Serving static /public/ file from Play 2 Scala controller

查看:58
本文介绍了从 Play 2 Scala 控制器提供静态/public/文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Play Framework 2 Scala 控制器提供静态文件的首选方法是什么?

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

该文件与我的应用程序捆绑在一起,因此不可能对文件系统绝对/path/to/the/file 进行硬编码,因为它的位置取决于 Play 应用程序的安装位置.

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.

文件放在 public/目录下,但不在 app/assets/下,因为我不想让 Play 编译它.

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

在我的 routes 文件中,我有这一行:

And in my routes file, I have this line:

<代码>GET//admin/controllers.Application.viewAdminPage

问题是在我的生产服务器上,发生了这个错误:
FileNotFoundException: app1/public/admin/index.html

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

除了Play.getFileOK.sendFile 之外,是否还有其他方法来指定要提供的文件?在生产中永远不会中断?

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

(我的应用程序安装在 /some-dir/app1/ 并且我从 /some-dir/ 启动它(没有 app1/>) — 如果我改为从 /some-dir/app1/ 启动应用程序,也许一切都会正常.但我想知道一个人应该"如何做,从内部提供静态文件控制器?这样一切都可以在生产服务器上运行,无论我从哪里启动应用程序)

(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)

推荐答案

Play 有一个内置的方法:

Play has a built-in method for this:

  Ok.sendResource("public/admin/file.html", classLoader)

您可以使用 environment.classLoader 从注入的 Environment 或从 this.getClass.getClassLoader 获取类加载器.

You can obtain a classloader from an injected Environment with environment.classLoader or from this.getClass.getClassLoader.

这篇关于从 Play 2 Scala 控制器提供静态/public/文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆