2011-03-27 37 views
0

我有一個JDO類和輔助類圖像以存儲一個字節數組內的圖像GSP,從數組字節圖像

JDO類:

@PersistenceCapable 
class Recipe{ 

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

     @Persistent 
     private String description 

     @Persistent(serialized = "true") 
     private Image 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頁面中顯示字節數組中的圖像?

+1

看起來像重複http://stackoverflow.com/questions/4502278/grails-displaying-created-image-in-gsp/4502403給我。我的答案可以幫助;) – 2011-03-28 08:32:01

+0

嗨維克多。感謝您的評論。在這個問題上我沒有看到你的建議。但這看起來正是我在尋找的東西。當我回家的時候會試試這個。謝謝 – superbly 2011-03-28 08:42:29

+0

這麼多善良的話,沒有一個upvote xD – 2011-03-28 09:04:25

回答

1

我有一個類似的用例在這裏,一個文件域類保存一個字節[]和上傳文件的元信息。要下載文件,我使用的是:

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的二級緩存關心它。如果您仍然有充分的理由不在下載請求中加載文件,則可以在先前的調用中將其存儲到http會話中。 在HTTP會話存儲這種的缺點:

  • 在許多併發會話,佔用大量內存
  • 的情況下,你會看到從休眠奇怪的例外(請務必爲!)
  • 一切存儲在http會話必須是可序列化的
+0

嗨感謝您的答案。希望能有另一種解決方案。 – superbly 2011-03-28 07:23:06