使用Play 2/Scala提供本地图像 [英] Serving local images with Play 2 / Scala

查看:76
本文介绍了使用Play 2/Scala提供本地图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to figure out a pattern for uploading and serving files (images) locally. I figured out the upload part, but a little confused on the storage and serve part.

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

I'm confused about how to display locally stored images on a single page using "Ok.sendFile". How do tie it into "img src" tags on the view? The other option I could think of is to run a (separate) web server locally just for storing files, which doesn't make much sense.

推荐答案

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

Just add an Action in a Controller that provides the image:

def picture(name: String) = Action {

   Ok.sendFile(new java.io.File(name)) // the name should contains the image extensions
}

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

Then add the corresponding route in your routes file:

GET /picture/:name  controllers.MyPictureController.picture(name: String)

您的HTML应该如下所示:

And your HTML should look like:

<img src="/picture/image.png">

或者如果您使用Scala模板:

or if you use the Scala templates:

<img src="@routes.controllers.MyPictureController.picture("image.png")">

这篇关于使用Play 2/Scala提供本地图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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