-1

I'm trying to store images in mongo after downloading it with request

here is my code which causes a corrupted image to be stored in db.

request('http://test.jpg', function (error, response, image) {

    db.images.insert(

        {
            file_name: 'test.jpg',
            image: new Buffer(image)
        },

        function(err){

           //mongojs callback

        }
    );
});

Please note I am using mongojs module and storing the images in regular document as BinData type.

Also if I write the image to a file, read it then save the image to the database then there is no corruption. But I don't want to do this as is my intention to avoid the file-system altogether.

I'm pretty this has something to do with encoding or buffers but I don't know enough about these to solve my problem.

saeed
  • 3,861
  • 3
  • 25
  • 23
  • If this code worked when you saved the image to a file and then read it back before saving it to the database, then the problem isn't likely to be with this part of the code, right? Or am I misunderstanding things? – JohnnyHK Sep 21 '12 at 23:50
  • I think the reason it works when I save to file-system then to the db is because the correct encoding or buffers is used. But when I do it directly am not setting this correctly. – saeed Sep 21 '12 at 23:58
  • In what way is the jpeg corrupted? Are you able to link to an original and corrupted image so someone could compare the differences? – Stennie Sep 24 '12 at 01:29

1 Answers1

0

If you don't want to use a proper image storing solution like gridfs you could base64 encode your images.

How can you encode a string to Base64 in JavaScript?

That gives you a string that you can store in mongo.

Community
  • 1
  • 1
Andy Chase
  • 1,318
  • 12
  • 23
  • 1
    He is storing the binary representation which is sufficient. Storing in base64 is for html pages etc and normal client side JS this is server side SJ in the form of node.js – Sammaye Sep 22 '12 at 11:30