使用Play 2/Scala提供本地图像

Tur*_*rar 4 scala playframework-2.0

我正试图找出一种在本地上传和提供文件(图像)的模式.我想出了上传部分,但对存储和服务部分有点困惑.

我对如何使用"Ok.sendFile"在单个页面上显示本地存储的图像感到困惑.如何将它绑定到视图中的"img src"标签?我能想到的另一个选择是在本地运行(单独的)Web服务器只是为了存储文件,这没有多大意义.

nde*_*rge 9

只需在提供图像的Controller中添加一个Action:

def picture(name: String) = Action {

   Ok.sendFile(new java.io.File(name)) // the name should contains the image extensions
}
Run Code Online (Sandbox Code Playgroud)

然后在routes文件中添加相应的路由:

GET /picture/:name  controllers.MyPictureController.picture(name: String)
Run Code Online (Sandbox Code Playgroud)

你的HTML应该是这样的:

<img src="/picture/image.png">
Run Code Online (Sandbox Code Playgroud)

或者如果您使用Scala模板:

<img src="@routes.controllers.MyPictureController.picture("image.png")">
Run Code Online (Sandbox Code Playgroud)