image - grails在文件夹中显示图像

标签 image grails gsp

我正在尝试使用Grails网络应用,现在我正在尝试显示文件夹中的所有图像。

为此,我需要执行以下操作:

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

因此,使用上面的代码,我使用以下方法显示一张图像:
<img class="thumbnail" src='${createLink(controller: "images", action: "display")}' />

使用此代码,我正在显示一张图像。
如何显示该文件夹中的所有图像?
我需要建立 list 吗?什么 list ?输出流列表?
在这种情况下,我应该在gsp文件中放入什么?

最佳答案

如果images文件夹位于应用程序结构内部,则可以直接创建指向该图像的链接。在这种情况下,我认为您需要一个 Controller 操作来输出一个文件的内容,而另一个操作则是获取图像列表并请求文件内容。

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>

附:代码未经测试,可能需要一些调整。

关于image - grails在文件夹中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15841547/

相关文章:

angularjs - Grails-无法将数据库状态与 session 同步

templates - Grails和gsp : How to render nested template with the same model/bean?

image - css 确定一个容器中的单个和多个图像

html - CSS:渲染图像时保持纵横比

android从zip文件中解压文件夹并从该文件夹中读取内容

PHP。 Imagecolorallocate 返回 false

grails - 在资源映射中嵌套常规URL映射时,可以更改生成的变量的名称吗?

validation - 如何停止grails清除自定义验证错误

Grails g :select optionValue

javascript - 将 javascript 变量传递给 gsp g :link tag