将图像文件发送回浏览器

时间:2013-09-06 13:26:36

标签: java spring servlets grails grails-2.0

我的应用程序有jpg图像文件显示在我的网站上。

在我的GSP中我做了:

<img class="itemThumImage border-radius-top-3px" src="${createLink(controller:'item', action:'getImage', id:item.id)}" />

我的ItemConroller的getImage操作是:

def getImage() {
   def item = Item.get(params.id)
   def file = new File(grailsApplication.parentContext.servletContext.getRealPath(item.id))

   response.setContentType("image/jpeg")
   response.setHeader("Content-disposition", "filename=\"${item.id}.jpg\"")
   response.setContentLength(fileBytes.size())
   response.outputStream << file.readBytes()
   response.outputStream.close()
}

这是将图像发送回浏览器的好方法吗?我认为图像被加载到堆中。我可以以某种方式加速这个过程吗?我最后一行是close()还是flush()或两者都需要?

1 个答案:

答案 0 :(得分:1)

这对开发/测试有好处(但在关闭响应后不要忘记return null)。

从不在生产系统上执行此操作。您需要在Tomcat前面使用前端服务器,如Nginx或Apache HTTPD服务器。

我推荐Nginx。对于Nginx,您可以使用以下配置来提供此文件:

location /item/getImage/ {
    alias /path/to/directory/with/images;
}

location / {
    //proxy to your Tomcat instance
    proxy_pass http://127.0.0.1:8080; 
}
相关问题