ch1ll
ch1ll

Reputation: 513

Saving images in mongodb as blob, React

I am using the dropzone-react component to upload pictures. After uploading, it gives me the blob:http://test address and if I open it I can see the picture i uploaded. What challenges me now is that I want to save this image as a blob-type into MongoDB.

This is my current code which is called after I chose a picture to upload. The files[0].preview shows the correct URL. Also console.log(blob) shows the blob in the console (but I can't find a data section, maybe that is the problem?

onFileDrop(files) {
    var xhr = new XMLHttpRequest();
    console.log(files[0].preview);
    xhr.open('GET', files[0].preview, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
        if (this.status == 200) {
            var blob = xhr.response;
            console.log(blob);
            Database.update({_id : _stateId}, { $push : {picture : blob}});
            }
        };
    xhr.send();

But after I update the database the picture element is just empty in the MongoDB. I tried saving xhr.response.type and this works, but I somehow have to access the data to store it inside MongoDB and retrieve it as a picture on another line in my code.

Am I missing some crucial step or is there even an easier approach to saving images in mongoDB by using react?

I am using the meteor framework, if that's an important information.

Upvotes: 2

Views: 6505

Answers (3)

Cheloide
Cheloide

Reputation: 805

I'm late to the party but instead of saving an image as blob, you could base64 encode it and then store the string in the database as plain text.

I have done this in past projects and storing a string is easier than storing/retrieving binary data in mongoDB.

The downside is that Base64 encoded binaries occupy about 37% more space than raw binaries.

Wikipedia article about Base64

Upvotes: 3

Mikkel
Mikkel

Reputation: 7777

I use a package called vsivsi:file-collection to store files/images in Mongo.

https://atmospherejs.com/vsivsi/file-collection

It includes example apps on how to do the file saving to your db in a griefs collection.

Upvotes: 1

Alberto Schiabel
Alberto Schiabel

Reputation: 1139

You should send your file to a REST endpoint of a server, and from the server you should send the image to your DB (MongoDB in this case).

Take a look at this example

Upvotes: 1

Related Questions