我很努力將圖像作爲字節數組存儲在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!)
乾杯 菲利普
「所以我會首先避免GridFS」......爲什麼?! – Alex
我只存儲小圖片,並且GridFS似乎沒有被插件支持,除非我錯了。 – Philippe
小圖像或不GridFS是要走的路。我不是Grails用戶,但是我發現了這個 - https://github.com/sergeyy/Grails-plugin-mongodb-gridfs – Alex