2

我正在努力将图像存储为 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" : " ", "版本" : 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)
}

我正在使用带有 mongo 插件的 Grails 2.2...

提前感谢您的提示(顺便说一句,2013 年快乐!)

干杯菲利普

4

2 回答 2

2

encodeBase64 / decodeBase64 是适合您的正确方法。

您提供的代码在以前的 mongo-gorm 插件版本中运行良好。在grails 2.2.01.1.0.GA mongodb数组没有正确转换的情况下,提交了错误GPMONGODB-265的情况。

考虑使用替代 gorm 插件或纯 groovy mongo 包装器gmongo

于 2013-01-29T21:31:23.397 回答
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()
于 2013-01-04T19:11:16.563 回答