Search code examples
httpgoiogridfs

http.Get() image from url and write into GridFS


I want to request an image from an url and write that image into a mongoDb GridFS database. The only working approach I got is to save the requested body to an file on OS and open it again.

...

response, err := http.Get("https://via.placeholder.com/350x150")

defer response.Body.Close()

file, _ := os.Create("file-name-placeholder.jpg")

b, _ := io.Copy(file, response.Body)

file.Close()

file, err = os.Open("file-name-placeholder.jpg")

gridFile, err := gridfs.Create("example-file.jpg")

_, err = io.Copy(gridFile, datei)

....

Is there a possibility to instantaneously write into GridFS?

Edit: I tried the shortway like @Vorsprung suggested. In this case there is an empty image in the database. As you can see, this first document has only length 0 and there is no document in the the db.images.chunks.find()collection for the first image-file.

> db.images.files.find()
{ "_id" : ObjectId("5bf0156b2f337b5b0636e711"), "chunkSize" : 261120, "uploadDate" : ISODate("2018-11-17T13:19:39.354Z"), "length" : 0, "md5" : "d41d8cd98f00b204e9800998ecf8427e", "filename" : "googlelogo_color_272x92dp.png" }
{ "_id" : ObjectId("5bf018a52f337b692d8cafd1"), "chunkSize" : 261120, "uploadDate" : ISODate("2018-11-17T13:33:25.208Z"), "length" : 5969, "md5" : "8f9327db2597fa57d2f42b4a6c5a9855", "filename" : "googlelogo_color_272x92dp.png" }

Solution

  • Have you tried io.Copy(gridFile, response.Body)? seems like an obvious short circuit