简体   繁体   中英

Upload file to MongoDB with mongo-go-driver using GridFS

I looked the official GridFS documentation, and did some google search but there isn't any clear documentation on using GridFS in the official mongo-go-driver.

So the further I could see is uploading the content of the file as below:

// Read the File
data, err := ioutil.ReadFile("data.txt")
check(err)
.....
// insert the collection to a document
uplodedResult, err := fileCollection.InsertOne(ctx, bson.D{
{"file", data},
})

How do I upload the file instead not only its contents.

So as per this documentation https://godoc.org/go.mongodb.org/mongo-driver/mongo/gridfs , we need to first create a new bucket with NewBucket() , than use OpenUploadStream() to initialize the upload stream, and finally we can upload the file with uploadStream.Write()

Here is the full source code of the solution https://gitlab.com/ykcab/mongo-gridfs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM