2015-05-10 81 views
0

我是Golang的新手。 我正在尝试检索已插入的PDF文件对象。我没有使用GridFS,因为我要存储的文件在16 MB以下。 该对象已被插入(使用load_file函数),而我在MongoDB可视客户端看到的对象ID是ObjectId(“554f98a400afc2dd3cbfb21b”)。Golang - MongoDB(mgo)检索插入的文件(BSON不是GridFS)

不幸的是,在磁盘上创建的文件为0 kb。 请指教如何正确检索插入的PDF对象。

谢谢

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")))) 
} 
+0

我改变了两个项目:一。 objectID:= bson.ObjectIdHex(The_ID)加上err = c.FindId(objectID).One(&result)和b。返回的对象是Raw类型,而不是RawDocElem。在此之后它正确保存了pdf。 – Tudor

回答

0

我想你打造的对象ID的方法是错误的。此外,您忘记测试FindId调用后的错误。

我会尝试导入BSON包,并使用类似构建对象ID:

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 
    ... 
} 
相关问题