2013-01-04 54 views
1

我很努力將圖像作爲字節數組存儲在Mongo中。 我的域名是相當簡單的Grails - Mongo:將圖像存儲爲字節數組

class Book { 
    String title 
    String author 
    byte[] photo 
    String photoType 
} 

的圖片均小於300KB,所以我會避免在首位GridFS的。 一旦持續,光好像被存儲爲字符串(總是11個字節)

db.book.find() { 「_id」:NumberLong(15), 「作者」: 「」, 「照片」: 「[B @ 774dba87」, 「照排機」: 「圖像/ JPEG」, 「標題」: 「」, 「版本」:0}

我的控制器讀取如下: DEF saveImage( ){

def bookInstance 
    if(request instanceof MultipartHttpServletRequest) { 

     MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; 
     CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("photo"); 

     params.photoType = file.getContentType() 
     print "nb bytes " +file.bytes.length //TODO 

     bookInstance = new Book(params) 
     bookInstance.photo=new byte[file.bytes.length] 
     bookInstance.photo = file.getBytes() 

     def okcontents = ['image/png', 'image/jpeg', 'image/gif'] 
     if (! okcontents.contains(file.getContentType())) { 
      flash.message = "Photo must be one of: ${okcontents}" 
      render(view:'create', model:[bookInstance:bookInstance]) 
      return; 
     } 

     log.info("File uploaded: " + bookInstance.photoType) 
    } 


    if (!bookInstance.save()) { 
     render(view:'create', model:[bookInstance:bookInstance]) 
     return; 
    } 
    flash.message = "Book Photo (${bookInstance.photoType}, ${bookInstance.photo.size()} bytes) uploaded." 
    redirect(action: "show", id: bookInstance.id) 
} 

我使用Grails 2.2與mongo插件...

預先感謝您的提示(快樂2013 BTW!)

乾杯 菲利普

+0

「所以我會首先避免GridFS」......爲什麼?! – Alex

+0

我只存儲小圖片,並且GridFS似乎沒有被插件支持,除非我錯了。 – Philippe

+0

小圖像或不GridFS是要走的路。我不是Grails用戶,但是我發現了這個 - https://github.com/sergeyy/Grails-plugin-mongodb-gridfs – Alex

回答

0
def imgStream = file.getInputStream() 
byte[] buf = new byte[310000] 
int len =imgStream.read(buf, 0, 310000) 
ByteArrayOutputStream bytestream = new ByteArrayOutputStream() 
while(len > 0) { 
    bytestream.write(buf, 0, len) 
    len =imgStream.read(buf, 0, 310000) 
} 
bookInstance.photo = bytestream.toByteArray() 
bookInstance.save() 
+0

我實際上找到了一個在字節數組上使用encodeBase64/decodeBase64的解決方案,在Mongo中存儲爲String 。謝謝你的幫助。 – Philippe

2

encodeBase64/decodeBase64是你正確的做法。

您提供的代碼在以前的mongo-gorm插件版本中工作正常。在grails 2.2.01.1.0.GA mongodb數組未正確轉換,錯誤GPMONGODB-265提交的案件。

考慮使用alternative gorm plugin或純groovy mongo包裝gmongo

相關問題