-2

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" }
tomole
  • 927
  • 3
  • 12
  • 35
  • 1
    There's no reason you shouldn't be able to copy the file directly. If it doesn't work for you, then you need to show a [mcve] demonstrating the issue. rather than the example of what you don't want to do. – JimB Nov 17 '18 at 15:20

1 Answers1

2

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

Vorsprung
  • 32,923
  • 5
  • 39
  • 63