3

我需要显示照片库。所以这是我的模板:

@(photos: List[Photo])

@title = {
  <bold>Gallery</bold>
}

@main(title,"photo"){
    <ul class="thumbnails">
    @for(photo <- photos) {
        <li class="span3">
            <a href="#" class="thumbnail">
                <img src="@photo.path" alt="">
            </a>
        </li>
    }
    </ul>
}

这是我的控制器方法:

public static Result getPhotos() {
    return ok(views.html.photo.gallery.render(Photo.get()));
}

这是我的照片豆:

    @Entity
    public class Photo extends Model {

@Id
public Long id;

@Required
public String label;

public String path;

public Photo(String path, String label) {
    this.path = path;
    this.label = label;
}

private static Finder<Long, Photo> find = new Finder<Long, Photo>(
        Long.class, Photo.class);

public static List<Photo> get() {
    return find.all();
}

public static Photo get(Long id) {
    return find.byId(id);
}

public static void create(Photo photo) {
    photo.save();
}

public static void delete(Long id) {
    find.ref(id).delete();
}

    }

我把照片绝对路径放在img节点的src属性中,但是不起作用。实现这一目标的最佳方法是什么?

PS:图像位于播放应用程序之外。

4

1 回答 1

5

看看我非常相似的问题:Direct serving files from outside of Play目录结构,最后我在非常基本的示例中使用了我的第二个建议,它可以显示为:

public static Result serve(String filepath){
    // some stuff if required
    return ok(new File("/home/user/files/"+filepath));
}

路线(使用星号*filepath允许字符串内部带有斜线):

GET   /files/*filepath    controllers.Application.serve(filepath : String)

视图(之前缺少@字符photo.path不是偶然的)

<img src="@routes.Application.serve(photo.path)" alt="@photo.alt" />

编辑:

You of course don't need to serve files trough the controller if you have any HTTP server and ability to create new subdomain/alias pointing to directory. In such case you can just store links as http://pics.domain.tld/holidays_2012/1.jpg or even better as holidays_2012/1.jpg (and then prefix it in the template with subdomain).

Finally you can set-up some alias ie. with Apache to use your domain.tld/* as pointer to Play app and domain.tld/pics/* as pointer to some folder

<VirtualHost *:80>
  ProxyPreserveHost On
  ServerName domain.tld
  ProxyPass  /pics !
  ProxyPass / http://127.0.0.1:9000/
  ProxyPassReverse / http://127.0.0.1:9000/

  Alias /pics/ /home/someuser/somefolder_with_pics/
  <Directory /home/someuser/somefolder_with_pics/>
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

in such case it's important to place ProxyPass /pics ! before ProxyPass / http://...

于 2012-06-04T15:58:36.730 回答