【问题标题】:gsp, image from array bytegsp,来自数组字节的图像
【发布时间】:2011-03-27 10:37:11
【问题描述】:

我有一个 JDO 类和一个帮助类 Image 来将图像存储在一个字节数组中

JDO 类:

@PersistenceCapable
class Recipe{

    @PrimaryKey
        @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
        private Long key

        @Persistent
        private String description

        @Persistent(serialized = "true")
        private Image image;
}

图像类:

class Image implements Serializable {

    private byte[] content
    private String filename
    private String mimeType
}

在 gsp 页面中,我遍历食谱并希望显示图像。 我可以做一个这样的控制器来获取图像 src。

 def viewImage= {
    //retrieve photo code here
    response.setHeader("Content-disposition", "attachment; filename=${photo.name}")
    response.contentType = photo.fileType //'image/jpeg' will do too
    response.outputStream << photo.file //'myphoto.jpg' will do too
    response.outputStream.flush()
    return;
  }

但是这样我必须将配方的密钥发送到这个控制器并再次从数据存储中加载图像。 (我实际上已经加载了它。但我认为我无法将此数据发送到控制器。我可以吗?) 有没有更方便的方式在 gsp 页面中显示字节数组中的图像?

【问题讨论】:

  • 对我来说看起来像是 stackoverflow.com/questions/4502278/… 的副本。我的回答可能会有所帮助;)
  • 你好维克多。感谢您的评论。我没有看到你在这个问题上的建议。但这看起来正是我正在寻找的。回家的时候试试这个。谢谢
  • 这么多好话,没有一个赞xD

标签: java grails gsp


【解决方案1】:

我在这里有一个类似的用例,一个 File 域类,其中包含一个字节 [] 和上传文件的元信息。要下载文件,我正在使用:

def fileDownload = {
    long id = params.id as long
    def file = File.get(id)
    assert file
    def fileName = URLEncoder.encode(file.name)
    response.addHeader("content-disposition", "attachment;filename=$fileName")
    response.contentType = file.contentType
    response.contentLength = file.data.size()
    response.outputStream << file.data
}

关于一遍又一遍地重新加载文件我不会太在意,Hibernate 2nd level 缓存关心它。如果您仍然有充分的理由不在下载请求中加载文件,您可以在之前的调用中将其存储到 http 会话中。 将其存储在 http 会话中的缺点:

  • 在许多并发会话的情况下,高内存消耗
  • 您会在 Hibernate 中看到奇怪的异常(一定要这样做!)
  • http 会话中存储的所有内容都必须是可序列化的

【讨论】:

  • 您好,感谢您的回答。不过希望有另一种解决方案。
猜你喜欢
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 2012-12-09
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
相关资源
最近更新 更多