0

Grails webapp を実行しようとしていますが、フォルダー内のすべての画像を表示しようとしています。

そのために、私は次のものを持っています:

def display(){
        def dir = new File("/tmp/images")
        def list = []
        dir.eachFileRecurse() { file ->
            def avatarFilePath = new File(file.path)
            response.setContentType("application/jpg")
            OutputStream out = response.getOutputStream();
            out.write(avatarFilePath.bytes);
            out.close();
        }
    }

上記のコードを使用して、次を使用して1つの画像を表示しています。

<img class="thumbnail" src='${createLink(controller: "images", action: "display")}' />

このコードを使用して、1 つの画像を表示しています。そのフォルダ内のすべての画像を表示するにはどうすればよいですか? リストを作成する必要がありますか? 何のリスト?出力ストリームのリスト? その場合、gsp ファイルには何を入れればよいでしょうか。

4

1 に答える 1

4

画像フォルダーがアプリ構造内にある場合は、画像へのリンクを直接作成できます。この場合、あるファイルの内容を出力するコントローラ アクションと、画像のリストを取得してファイルの内容を要求する別のアクションが必要だと思います。

class MyController {
  private static final File IMAGES_DIR = new File('/tmp/images')

  //get the list of files, to create links in the view
  def listImages() {
    [images: IMAGES_DIR.listFiles()]
  }
  //get the content of a image
  def displayImage() {
    File image = new File(IMAGES_DIR.getAbsoluteFilePath() + File.separator + params.img)
    if(!image.exists()) {
      response.status = 404
    } else {
      response.setContentType("application/jpg")
      OutputStream out = response.getOutputStream();
      out.write(avatarFilePath.bytes);
      out.close();
    }
  }

}

そして、あなたのgspは次のようなことができます

<g:each in="${images}" var="img">
  <img class="thumbnail" src='${createLink(controller: "myController", action: "displayImage", params:[img: img.name])}' />
</g:each>

PS: コードはテストされていません。調整が必要な場合があります。

于 2013-04-05T19:30:15.377 に答える