Grails - Mongo:将图像存储为字节数组

时间:2013-01-04 16:06:45

标签: mongodb grails grails-plugin

我正在努力将图像存储为Mongo中的字节数组。 我的域名很简单

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

图像都低于300kB,所以我首先要避免使用GridFS。 一旦持久化,照片似乎存储为一个字符串(总是11个字节)

  

db.book.find()       {“_ id”:NumberLong(15),“author”:“”,“photo”:“[B @ 774dba87”,“photoType”:“image / jpeg”,“title”:“”,“version”: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年快乐!)

干杯 菲利普

2 个答案:

答案 0 :(得分:2)

encodeBase64 / decodeBase64是您的正确方法。

您提供的代码在之前的mongo-gorm插件版本中运行良好。在grails 2.2.01.1.0.GA mongodb数组未正确转换时,GPMONGODB-265为该案例提交了错误。

考虑使用alternative gorm plugin或纯groovy mongo包装gmongo

答案 1 :(得分: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()