dongmuyan5638
2015-05-10 18:55
浏览 65

Golang-MongoDB(mgo)检索插入的文件(BSON不是GridFS)

I am a newbie in Golang. I am trying to retrieve a PDF file object I have inserted. I am not using GridFS, as the files that I would be storing are under 16 MB. The object has been inserted (using load_file function) and the object ID I am seeing with the MongoDB visual client is ObjectId("554f98a400afc2dd3cbfb21b").

Unfortunately the file created on disk is of 0 kb. Please advise how to correctly retrieve the inserted PDF object.

Thank you

package main

import (
    "fmt"
    "io/ioutil"

    "gopkg.in/mgo.v2"
)

type Raw struct {
    Kind byte
    Data []byte
}

type RawDocElem struct {
    Name  string
    Value Raw
}

func check(err error) {
    if err != nil {
        panic(err.Error())
    }
}

func read_file_content(AFileName string) []byte {

    file_contents, err := ioutil.ReadFile(AFileName)
    check(err)
    return file_contents
}

func save_fetched_file(AFileName RawDocElem) {
    ioutil.WriteFile("fisier.pdf", AFileName.Value.Data, 0644)
    fmt.Println("FileName:", AFileName.Name)
}

func load_file(AFileName string, ADatabaseName string, ACollection string) {
    session, err := mgo.Dial("127.0.0.1,127.0.0.1")

    if err != nil {
        panic(err)
    }
    defer session.Close()

    session.SetMode(mgo.Monotonic, true)

    c := session.DB(ADatabaseName).C(ACollection)

    the_obj_to_insert := Raw{Kind: 0x00, Data: read_file_content(AFileName)}

    err = c.Database.C(ACollection).Insert(&the_obj_to_insert)
    check(err)

}

func get_file(ADatabaseName string, ACollection string, The_ID string) RawDocElem {
    session, err := mgo.Dial("127.0.0.1,127.0.0.1")

    if err != nil {
        panic(err)
    }
    defer session.Close()

    session.SetMode(mgo.Monotonic, true)
    c := session.DB(ADatabaseName).C(ACollection)

    result := RawDocElem{}
    err = c.FindId(The_ID).One(&result)
    return result
}

func main() {
    //f_name := "Shortcuts.pdf"
    db_name := "teste"
    the_collection := "ColectiaDeFisiere"
    //load_file(f_name, db_name, the_collection)
    fmt.Sprintf(`ObjectIdHex("%x")`, string("554f98a400afc2dd3cbfb21b"))
    save_fetched_file(get_file(db_name, the_collection, fmt.Sprintf(`ObjectIdHex("%x")`, string("554f98a400afc2dd3cbfb21b"))))
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanluangua8850 2015-05-11 11:52
    已采纳

    I think your way to build the object ID is wrong. Furthermore, you forgot to test the error following the FindId call.

    I would try to import the bson package, and build the object ID using something like:

    hexString := "554f98a400afc2dd3cbfb21b" //24 digits hexadecimal string
    objid := bson.ObjectIdHex(hexString)
    ...
    err = c.FindId(objid).One(&result)
    if err == nil {
       // Do something with result
       ...
    } else {
       // Error
       ...
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题