Attachments in Couchbase DB

52 views
Skip to first unread message

Abhishek Shetty

unread,
Nov 9, 2014, 11:30:59 PM11/9/14
to mobile-c...@googlegroups.com
  
    How do I attach and get images from Couchbase DB . I am using a sync gateway to sync the data from the Couchbase DB to the Couchbase Lite.
    I need to do it from the javascript prespective. I know that the images will get stored as base64 format. But the main issue I am facing is I am not being
    able to convert the binary data back to viewable image .

    Below is the code snippet I have for getting the attachments(images)

    config.db.get(id,{attachments:true},function(err, doc){
            var imgContent = "";
            if(err){
                alert(JSON.stringify(err)) ;               
            }else{
                var name = doc.imgName
                var fields = Object.keys(doc), o, attachments;
                if(doc){
                    fields.map( function (f) {
                        if (f == '_attachments') {
                            attachments = doc[f];
                            for (o in attachments) {
                                imgContent= "<img style='width:100%;height:100%;' src=data:"+attachments[o].content_type+";base64,"+attachments[o].data+">";
                            }
                        }   
                    });
                }
            }
            $("#locations").html(imgContent);
        });

       Regards
       Abhishek

Jens Alfke

unread,
Nov 10, 2014, 1:28:16 PM11/10/14
to mobile-c...@googlegroups.com
On Nov 9, 2014, at 8:30 PM, Abhishek Shetty <misternic...@gmail.com> wrote:

    I know that the images will get stored as base64 format.

If images are stored as document attachments, they won't be encoded in base64 in the database. It's true that if you GET the document with ?attachments=true the data will appear as base64 properties in the _attachments object, but you really don't want to do that; it's inefficient, especially with big data like images.

But the main issue I am facing is I am not being able to convert the binary data back to viewable image . 

Not sure what's wrong with your code; I'm not a JavaScript expert. But it's definitely not a good way to load or display images!

What you should do instead is take advantage of the fact that every attachment has its own URL: /db/docID/attachmentName. So once you have the image name all you have to do is append it to the document's URL (with a slash in between) and set that as the SRC attribute of an IMG element.

—Jens
Reply all
Reply to author
Forward
0 new messages