Saving pdf in MongoDb using GoLang mgo

孤街醉人 提交于 2019-12-02 08:03:35

The file returned by Request.FormFile() is of type multipart.File which is:

type File interface {
    io.Reader
    io.ReaderAt
    io.Seeker
    io.Closer
}

It implements io.Reader, so you can simply read its content e.g. with ioutil.ReadAll():

data, err := io.ReadAll(file)
// Handle error

Then:

dbSchoolPojo.Pdfdata = data

But storing big files as part of documents is not optimal / efficient. Instead take a look at the MongoDB GridFS that is also supported by mgo: Database.GridFS().

Here's how you can store a file in MongoDB GridFS (example taken from GridFS.Create()):

func check(err error) {
    if err != nil {
        panic(err.String())
    }
}
file, err := db.GridFS("fs").Create("myfile.txt")
check(err)
n, err := file.Write([]byte("Hello world!"))
check(err)
err = file.Close()
check(err)
fmt.Printf("%d bytes written\n", n)

Using GridFS, you can also save the file without having to read all its content into memory first, if you "stream" the file content into the mgo.GridFile, as it implements io.Writer. Call io.Copy():

// ...
file, handler, err := r.FormFile("pdfFile")

// ...
mongoFile, err := db.GridFS("fs").Create("somepdf.pdf")
check(err)

// Now stream from HTTP request into the mongo file:
written, err := io.Copy(mongoFile, file)
// Handle err

err = mongoFile.Close()
check(err)

Edit: update answering your update

When you serve the PDF, you query the document in a wrong way:

err := coll.Find(bson.M{"_id": bson.ObjectIdHex(incomingId)}).
    Select(bson.M{"pdf": 1}).One(&school)

You select the pdf field to retrieve, but your documents in MongoDB have no such field:

type dbSchool struct {
    ID  bson.ObjectId  `json:"id" bson:"_id,omitempty"`
    ...
    Pdfdata  []byte  `json:"pdf"`
    ...
}

This type definition will result having a pdfdata field, but not pdf. Add the proper mgo struct tag:

type dbSchool struct {
    ID  bson.ObjectId  `json:"id" bson:"_id,omitempty"`
    ...
    Pdfdata  []byte  `json:"pdf" bson:"pdf"`
    ...
}

Or change the selected field from pdf to pdfdata.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!