【问题标题】:Grails - Mongo: storing images as byte arrayGrails - Mongo:将图像存储为字节数组
【发布时间】:2013-01-04 16:06:44
【问题描述】:

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

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

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

db.book.find() {“_id”:NumberLong(15),“作者”:“”,“照片”:“[B@774dba87”,“photoType”:“图像/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)
}

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

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

干杯 菲利普

【问题讨论】:

  • “所以我会首先避免使用 GridFS”...为什么?!
  • 我只存储小图,GridFS好像不被插件支持,除非我记错了。
  • 小图像与否,GridFS 是要走的路。我不是 Grails 用户,但我发现了这个 - github.com/sergeyy/Grails-plugin-mongodb-gridfs

标签: mongodb grails grails-plugin


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:
    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()
    

    【讨论】:

    • 我实际上找到了一个在字节数组上使用 encodeBase64 / decodeBase64 的解决方案,在 Mongo 中存储为字符串。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多