0

Alright, so I have an image at a specific URL with the variable path, I want to download it and store it in CollectionFS. How can I get/create the image buffer from the response?

var request = Npm.require('request').defaults({encoding: null});
request.get(path, function(err, res, body)
    {
        return CollectionFS.storeBuffer(res.request.uri.path, body, { 
    });
});

It appears to store successfully, with the correct size. But when I try to view the image it appears to be corrupted.

puttputt
  • 1,259
  • 2
  • 14
  • 25

1 Answers1

0

Answering my own question. I had two issues with the above code. Firstly, meteor doesn't like it when you try to touch the database inside of a callback, so I added a future to wait until the callback was done.

Secondly, the default encoding on storeBuffer is utf-8 - which is a problem for images. Changing it to ascii solved my problem.

var Future = Npm.require("fibers/future");

    var pre = new Future();
    var preOnComplete = pre.resolver();

    var request = Npm.require('request').defaults({encoding: null});

    request.get(path, function(err, res, body)
    {
        return preOnComplete(err, res, body);
    });

    Future.wait(pre);

    return EventImages.storeBuffer(pre.value.request.href, pre.value.body, { 
        contentType: 'image/jpeg',
        metadata: { eventId: eventId },
        encoding: 'binary'
    });
puttputt
  • 1,259
  • 2
  • 14
  • 25