我的应用程序有 jpg 图像文件显示在我的网站上。
在我的普惠制中,我这样做:
<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()
或者两者都需要?
最佳答案
这对于开发/测试很有好处(但不要忘记在关闭响应后返回 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;
}
关于java - 将图像文件发送回浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18658990/