我正在尝试使用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/